An Inheritance Example
The “inheritance concept” is grouped into two categories:
- Subclass (child): the class that inherits from another class, and
- Superclass (parent): the class being inherited from.
To inherit from a class, use the extends
keyword.
The Java inheritance is demonstrated in the following example, which includes three classes namely Calculator
, Increment
, and Calculation
.
Using extends
keyword, the Calculation
inherits the method add
of Increment
class.
In addition, the Calculation
overrides the method inc
of Increment
class.
When an object of
Calculation
class is created, a copy of the contents of the superclass is made within it.
That is why, using the object of the subclass you can access the members of a superclass.
The superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below.
But using the superclass reference variable (
demo
in this case) you cannot call the method
multiply
, which belongs to the subclass
Calculation
:
Increment demo = new Calculation( );
demo.inc( a );
demo.add( a, b );
demo.multiply( a, b ); // Error
Note that a subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.