Java Reference
In-Depth Information
I NHERITANCE AND O BJECTS
From a conceptual perspective, each subclass, in a sense, contains its superclass
(i.e., its parent class).
Think about it this way. Each instance of a subclass automatically creates an in-
stance of its parent class. Therefore, an object whose class type is a derived class log-
ically has its own identity and its parent's identity. Both the base object and the
derived object are instantiated (created) when the derived object is instantiated. Af-
terward, the derived object can call functions in the base object without first creat-
ing the base object.
In the same way, a class (or program) that creates and uses a derived class can di-
rectly call methods in the superclass without explicitly creating the superclass. This
is because all of the superclass's public methods become public methods of the sub-
class. The subclass can add its own members or modify the behavior of existing
methods, but by default, the subclass contains all of the functions of the parent class.
Java actually loads both the base object(s) and the derived object at the same time.
It then calls the constructor for each class in hierarchal order, so only one object re-
ally exists. But when coding a class inheritance hierarchy, it is helpful to think about
a derived class as “containing” its super classes, as you will see in a few pages.
I NHERITING M ETHODS
Suppose that the ErrorMsg class is derived from a TextMessage class, and TextMes-
sage contains a public method called getTranslation . This method returns a trans-
lated version of the message. ErrorMsg defines only one public method, named
getErrorMsg . Even so, ErrorMsg appears to have two public methods,
getErrorMsg and getTranslation , as shown in Figure 5.2.
 
Search WWH ::




Custom Search