Java Reference
In-Depth Information
Ask the Expert
Q :
When should I make an instance variable private?
A : There are no hard and fast rules, but here are two general principles. If an instance
variable is to be used only by methods defined within its class, then it should be
made private. If an instance variable must be within certain bounds, then it should be
private and made available only through accessor methods. This way, you can pre-
vent invalid values from being assigned.
Constructors and Inheritance
In a hierarchy, it is possible for both superclasses and subclasses to have their own con-
structors. This raises an important question: What constructor is responsible for building
an object of the subclass—the one in the superclass, the one in the subclass, or both? The
answer is this: The constructor for the superclass constructs the superclass portion of the
object, and the constructor for the subclass constructs the subclass part. This makes sense
because the superclass has no knowledge of or access to any element in a subclass. Thus,
their construction must be separate. The preceding examples have relied upon the default
constructors created automatically by Java, so this was not an issue. However, in practice,
most classes will have explicit constructors. Here you will see how to handle this situation.
When only the subclass defines a constructor, the process is straightforward: simply con-
struct the subclass object. The superclass portion of the object is constructed automatic-
ally using its default constructor. For example, here is a reworked version of Triangle that
defines a constructor. It also makes style private, since it is now set by the constructor.
Search WWH ::




Custom Search