Java Reference
In-Depth Information
// #2 - "extends Object" is explicitly added for class P
public class P extends Object {
// Code for class P goes here
}
In the previous chapters, you did not use the extends clause to declare your classes. They were implicitly
inherited from the Object class. This is the reason that objects of those classes were able to use the methods of the
Object class. Consider the following snippet of code:
Employee emp = new Employee();
int hc = emp.hashCode();
String str = emp.toString();
Note that the Employee class does not specify its superclass using an extends clause. This means that it inherits
from the Object class. The Object class declares the hashCode() and toString() methods. Because the Employee
class is implicitly a subclass of the Object class, it can use these methods as if they have been included in its own
declaration. You have been using inheritance from the very first Java program you wrote, although you were not aware
of it. This section has demonstrated the power of inheritance that comes as code reuse. You will see other benefits of
inheritance later in this chapter.
Inheritance and Hierarchical Relationship
I touched upon this point in the previous section that inheritance should be used only if an “is-a” relationship exists
between the subclass and the superclass. A subclass can have its own subclasses, which in turn can have their own
subclasses, and so on. All classes in an inheritance chain form a tree-like structure, which is known as an inheritance
hierarchy or a class hierarchy. All classes above a class in the inheritance hierarchy are called ancestors for that class.
All classes below a class in the inheritance hierarchy are called descendants of that class.
Java allows single inheritance for a class. That is, a class can have only one superclass (or parent). However, a
class can be the superclass for multiple classes. All classes in Java have a superclass except the Object class. The
Object class sits at the top of the inheritance hierarchies for all classes in Java. Figure 16-1 shows a sample inheritance
hierarchy for the Employee class and its descendants using a UML (Unified Modeling Language) diagram. In a UML
diagram, a superclass and a subclass are connected using an arrow pointing from the subclass to the superclass.
Figure 16-1. A sample inheritance class hierarchy
 
Search WWH ::




Custom Search