|Navigate Classes and Objects topic: )|
The inheritance is one of the most powerful mechanism of the Object Oriented Programming. It allows to reuse the members of a class (called the superclass or the mother class) in another class (called subclass, child class or the derived class) that inherit from it. This way, classes can be built by successive inheritance.
In Java, this mechanism is enabled by the
extends keyword. Example:
|Code listing 4.9: Vehicle.java
|Code listing 4.10: Car.java
In the Code listing 4.10, the class
Car inherits from
Vehicle, which means that the attributes
numberOfSeats are present in the class
Car, whereas they are defined in the class
Vehicle. Also, the constructor defined in the class
Car allows to initialize those attributes. In Java, the inheritance mechanism allows to define a class hierarchy with all the classes. Without explicit inheritance, a class implicitly inherits from the
Object class. This
Object class is the root of the class hierarchy.
Some classes can't be inherited. Those classes are defined with the
final keyword. For instance, the
Integer class can't have subclasses. It is called a final class.
At the instantiating, the child class receives the features inherited from its superclass, which also has received the features inherited from its own superclass and so on to the
Object class. This mechanism allows to define reusable global classes, whose user details the behavior in the derived more specific classes.
In Java, a class can only inherit from one class. Java does not allow you to create a subclass from two classes, as that would require creating complicated rules to disambiguate fields and methods inherited from multiple superclasses. If there is a need for Java to inherit from multiple sources, the best option is through interfaces, described in the next chapter.
The super keyword
|Code listing 4.11: Plane.java
In this example, the constructor of the
Plane class calls the constructor of its superclass
Vehicle. You can only use
super to access the members of the superclass inside the child class. If you use it from another class, it accesses the superclass of the other class. This keyword also allows you to explicitly access the members of the superclass, for instance, in the case where there is a method with the same name in your class (overriding, ...). Example :
|Code listing 4.12: Vehicle.java
|Code listing 4.13: Plane.java
- See also the Object Oriented Programming book about the inheritance concept.