Java Reference
In-Depth Information
Display 4.10
Encapsulation
An encapsulated class
Implementation details
hidden in the capsule:
Private instance variables
Private constants
Private methods
Bodies of public and
private method definitions
Interface available to a
programmer using the class:
Comments
Headings of public accessor,
mutator, and other methods
Public defined constants
Programmer who
uses the class
A class definition should have
no public instance variables.
TIP: A Class Has Access to Private Members of
All Objects of the Class
Consider the definition of the method
equals
for the class
DateFifthTry
, given in
Display 4.9 and repeated as follows:
public boolean
equals(DateFifthTry otherDate)
{
return
( (month.equalsIgnoreCase(otherDate.month))
&& (day == otherDate.day) &&
(year == otherDate.year));
}
You might object that
otherDate.month
,
otherDate.day
, and
otherDate.year
are illegal because
month
,
day
, and
year
are private instance variables of some object
other than the calling object. Normally, that objection would be correct. However, the
object
otherDate
is of the same type as the class being defi ned, so this is legal. In the
defi nition of a class, you can access private members of any object of the class, not just
private members of the calling object.
(continued)