Java – Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.

Syntax

class Super {
   .....
   .....
}
class Sub extends Super {
   .....
   .....
}

Sample Code

Following is an example demonstrating Java inheritance. In this example, you can observe two classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of Calculation class.

Copy and paste the following program in a file with name My_Calculation.java

Example

classCalculation{int z;publicvoid addition(int x,int y){
      z = x + y;System.out.println("The sum of the given numbers:"+z);}publicvoidSubtraction(int x,int y){
      z = x - y;System.out.println("The difference between the given numbers:"+z);}}publicclassMy_CalculationextendsCalculation{publicvoid multiplication(int x,int y){
      z = x * y;System.out.println("The product of the given numbers:"+z);}publicstaticvoid main(String args[]){int a =20, b =10;My_Calculation demo =newMy_Calculation();
      demo.addition(a, b);
      demo.Subtraction(a, b);
      demo.multiplication(a, b);}}

Compile and execute the above code as shown below.

javac My_Calculation.java
java My_Calculation

After executing the program, it will produce the following result −

Output

The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

In the given program, when an object toMy_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.

Inheritance

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 ( cal in this case) you cannot call the method multiplication(), which belongs to the subclass My_Calculation.

Calculation cal =newMy_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

Note − 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.

Leave a comment