Java Reference
In-Depth Information
The following rules about superclasses and subclasses should be kept in mind:
1. The
private
members of the superclass are
private
to the superclass;
hence, the members of the subclass(es) cannot access them directly. In
other words, when you write the definitions of the methods of the
subclass, you cannot access the
private
members of the superclass
directly. (The next section explains how to access the
private
members
of a superclass in its subclass.)
2. The subclass can directly access the
public
members of the superclass.
3. The subclass can include additional data and/or method members.
4. The subclass can override, that is, redefine, the
public
methods of the
superclass. In the subclass, you can have a method with the same name,
number, and types of parameters as a method in the superclass. How-
ever, this redefinition is available only to the objects of the subclass, not
to the objects of the superclass.
5. All data members of the superclass are also data members of the subclass.
Similarly, the methods of the superclass (unless overridden) are also the
methods of the subclass. (Remember Rule 1 when accessing a member
of the superclass in the subclass.)
Each subclass, in turn, may become a superclass for a future subclass. Inheritance can be
either single or multiple. In single inheritance, the subclass is derived from a single
superclass; in multiple inheritance, the subclass is derived from more than one super-
class. Java supports only single inheritance; that is, in Java a class can extend the definition of
only one class.
The next sections describe two important issues related to inheritance. The first issue is
using the methods of a superclass in its subclass. While discussing this issue, we will also
address how to access the
private
(data) members of the superclass in the subclass. The
second key inheritance issue is related to the constructor. The constructor of a subclass
cannot directly access the
private
data members of the superclass. Thus, you must ensure
that
private
data members that are inherited from the superclass are initialized when a
constructor of the subclass executes.
Suppose that a
class
SubClass
is derived from a
class
SuperClass
. Further assume
that both
SubClass
and
SuperClass
have some data members. It then follows that the
data members of the
class
SubClass
are its own data members, together with the data
members of
SuperClass
. Similarly, in addition to its own methods, the subclass also
inherits the methods of the superclass. The subclass can give some of its methods the same
signature as given by the superclass. For example, suppose that
SuperClass
contains a
method,
print
, that prints the values of the data members of
SuperClass
.
SubClass
contains data members in addition to the data members inherited from
SuperClass
.
Suppose that you want to include a method in
SubClass
that prints the data members of
Search WWH ::
Custom Search