Inheritance
Inheritance
Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass
that have been declared as private.
plainbox = weightbox;
(superclass) (subclass)
SUPERCLASS ref = new SUBCLASS(); // HERE ref can only access methods which are
available in SUPERCLASS
Using super:
Whenever a subclass needs to refer to its immediate superclass, it can do so by use
of the keyword super.
super has two general forms. The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This causes the
Box constructor to be called,
which initializes width, height, and depth using these values. BoxWeight no longer
initializes these values itself.
It only needs to initialize the value unique to it: weight. This leaves Box free to
make these values private if desired.
Thus, super( ) always refers to the superclass immediately above the calling class.
This is true even in a multileveled hierarchy.
class Box {
private double width;
private double height;
private double depth;
super.member
Here, member can be either a method or an instance variable. This second form of
super is most applicable to situations
in which member names of a subclass hide members by the same name in the
superclass.
super( ) always refers to the constructor in the closest superclass. The super( )
in BoxPrice calls the constructor in
BoxWeight. The super( ) in BoxWeight calls the constructor in Box. In a class
hierarchy, if a superclass constructor
requires parameters, then all subclasses must pass those parameters “up the line.”
This is true whether or not a
subclass needs parameters of its own.
If you think about it, it makes sense that constructors complete their execution in
order of derivation.
Because a superclass has no knowledge of any subclass, any initialization it needs
to perform is separate from and
possibly prerequisite to any initialization performed by the subclass. Therefore,
it must complete its execution first.