Java Reference
In-Depth Information
Here,
Triangle
's constructor initializes the members of
TwoDClass
that it inherits along
with its own
style
field.
When both the superclass and the subclass define constructors, the process is a bit more
complicated because both the superclass and subclass constructors must be executed. In
this case, you must use another of Java's keywords,
super
, which has two general forms.
The first calls a superclass constructor. The second is used to access a member of the su-
perclass that has been hidden by a member of a subclass. Here, we will look at its first use.
Using super to Call Superclass Constructors
A subclass can call a constructor defined by its superclass by use of the following form of
super
:
super(
parameter-list
);
Here,
parameter-list
specifies any parameters needed by the constructor in the superclass.
super( )
must always be the first statement executed inside a subclass constructor. To see
how
super( )
is used, consider the version of
TwoDShape
in the following program. It
defines a constructor that initializes
width
and
height
.