Java Reference
In-Depth Information
Relationships between Parent and Child Classes
Just as a human parent is a child of his or her own parent, so
a parent class can be a child of another class, thus inheriting
features from its parent class.
Furthermore, although PasswordException is shown as the root in the
example of the inheritance hierarchy in Figure 10-3 on the previous page, it is
also a subclass, as it inherits from the Exception class. The Exception class, in
turn, inherits from the Throwable class, the superclass class for all errors and
exceptions in Java, and ultimately from the Object class, the root for all objects
in Java (Figure 10-4). A PasswordSizeException also is a PasswordException, an
Exception, and most generically, an Object.
Although methods can be inherited by a subclass, a subclass does not inherit
the constructor methods of its superclass. When a subclass constructor is called,
it must call a superclass constructor as its first action, so that the superclass may
initialize its instance variables. Recall that the method, super(), is how a subclass
explicitly calls a superclass constructor, using appropriate arguments, if any. If
the superclass has a default constructor, then no explicit call is needed, as the
compiler inserts an implicit call to the superclass default constructor.
Object
Throwable
Exception
Single versus Multiple Inheritance
Java has specific rules regarding inheritance. You may have noticed that the
inheritance hierarchy is like a single-sided (one parent) family tree. Java supports
single, rather than multiple, inheritance. Single inheritance means that an
object can inherit from only a single parent. Some object-oriented languages,
such as C++, support multiple inheritance , where an object can inherit from
more than one parent. Using multiple inheritance introduces some problems,
such as how to handle instance variables with the same name that were inherited
from multiple parents. Even more complex is how to handle inheritance from
multiple parents when the parents ultimately have a common parent! Java avoids
these problems by supporting only single inheritance.
PasswordException
usage()
FIGURE 10-4
Single Inheritance versus Multiple Inheritance
Java supports only single inheritance for classes, preventing
conflict from definitions of the same methods in parent classes.
Interfaces, however, may use multiple inheritance, as their
methods only can be abstract.
Class Inheritance versus Implementing Interfaces
As you have learned, when a subclass inherits from a superclass, it may
inherit both variables and methods. For example, if your program extends the
Applet class, then your program is an Applet and has all of the expected capabili-
ties of an Applet. That program also may need to listen for, or receive notice
about, certain actions, such as when a user clicks a button. If Java allowed
 
Search WWH ::




Custom Search