Java Reference
In-Depth Information
Some programmers like the
protected
access feature because it seems to strike
a balance between absolute protection (making all fields private) and no protection
at all (making all fields public). However, experience has shown that protected
fields are subject to the same kinds of problems as public fields. The designer of
the superclass has no control over the authors of subclasses. Any of the subclass
methods can corrupt the superclass data. Furthermore, classes with protected fields
are hard to modify. Even if the author of the superclass would like to change the
data implementation, the protected fields cannot be changed, because someone
somewhere out there might have written a subclass whose code depends on them.
464
465
In Java, protected fields have another drawbackȌthey are accessible not just by
subclasses, but also by other classes in the same package.
It is best to leave all data private. If you want to grant access to the data to subclass
methods only, consider making the accessor method protected.
10.8 Object: The Cosmic Superclass
In Java, every class that is defined without an explicit
extends
clause automatically
extends the class
Object
. That is, the class
Object
is the direct or indirect
superclass of every class in Java (see
Figure 8
).
Of course, the methods of the
Object
class are very general. Here are the most
useful ones:
Method
Purpose
String toString()
Returns a string representation of
the object
boolean equals(Object
otherObject)
Tests whether the object equals
another object
Object clone()
Makes a full copy of an object
It is a good idea for you to override these methods in your classes.