Java Reference
In-Depth Information
You should declare all instance fields as private.
public class BankRobber
{
public static void main(String[] args)
{
BankAccount momsSavings = new
BankAccount(1000);
. . .
momsSavings.balance = -1000; // Error
}
}
Encapsulation is the process of hiding object data and providing methods for data
access.
In other words, if the instance fields are declared as private, then all data access must
occur through the public methods. Thus, the instance fields of an object are
effectively hidden from the programmer who uses a class. They are of concern only
to the programmer who implements the class. The process of hiding the data and
providing methods for data access is called encapsulation. Although it is theoretically
possible in Java to leave instance fields public, that is a very uncommon practice. We
will always make instance fields private in this topic.
94
95
S YNTAX 3.4 Instance Field Declaration
accessSpecifier class ClassName
{
. . .
accessSpecifier fieldType fieldName;
. . .
}
Example:
public class BankAccount
{
. . .
private double balance;
. . .
Search WWH ::




Custom Search