Java Programming/Inheritance

Inheritance is one of the most powerful mechanisms of the Object Oriented Programming. It allows the reuse of the members of a class (called the superclass or the mother class) in another class (called subclass, child class or the derived class) that inherits from it. This way, classes can be built by successive inheritance.

In Java, this mechanism is enabled by the keyword. Example:

In the Code listing 4.10, the class  inherits from , which means that the attributes   and   are present in the class  , whereas they are defined in the class. Also, the constructor defined in the class  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  class. This  class is the root of the class hierarchy.

Some classes can't be inherited. Those classes are defined with the keyword. For instance, the  class can't have subclasses. It is called a final class.

The 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  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
The keyword allows access to the members of the superclass of a class, as you can use  to access the members of the current class. Example:

In this example, the constructor of the  class calls the constructor of its superclass. You can only use 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 :

Question 4.1: Consider the following classes.

List all the attributes and methods that can be accessed in the class.

inherits from  and   but not from.


 * See also the Object Oriented Programming book about the inheritance concept.