Java Reference
In-Depth Information
LISTING 9.6
continued
public int
getDefinitions ()
{
return
definitions;
}
}
The
Dictionary2
constructor takes two integer values as parameters, repre-
senting the number of pages and definitions in the topic. Because the
Book2
class
already has a constructor that performs the work to set up the parts of the diction-
ary that were inherited, we rely on that constructor to do that work. However,
since the constructor is not inherited, we cannot invoke it directly, and so we use
the
super
reference to get to it in the parent class. The
Dictionary2
constructor
then proceeds to initialize its
definitions
variable.
In this case, it would have been just as easy to set the
pages
variable explic-
itly in the
Dictionary2
constructor instead of using
super
to call the
Book2
constructor. However, it is good practice to let each class “take care of itself.”
If we choose to change the way that the
Book2
constructor sets up its
pages
variable, we would also have to remember to make that change in
Dictionary2
.
By using the
super
reference, a change made in
Book2
is automatically reflected
in
Dictionary2
.
A child's constructor is responsible for calling its parent's constructor.
Generally, the first line of a constructor should use the
super
reference call to
a constructor of the parent class. If no such call exists, Java will automatically
make a call to
super
()
at the beginning of the constructor. This rule ensures
that a parent class initializes its variables before the child class constructor
begins to execute. Using the
super
reference to invoke a parent's constructor
can be done only in the child's constructor, and if included it must be the first
line of the constructor.
The
super
reference can also be used to reference other variables and meth-
ods defined in the parent's class. We use this technique in later sections of this
chapter.
Java's approach to inheritance is called
single inheritance.
This term means that
a derived class can have only one parent. Some object-oriented languages allow a
Search WWH ::
Custom Search