Inheritance in Java | Example, Use, Advantage

In this tutorial, we will learn a very important topic inheritance in Java.

We will cover Is-A relationship, inheritance reusability features, uses, and advantages with real-time examples.

Inheritance is one of the main four pillars (core concepts) of OOPs (Object Oriented Programming) concepts in Java. It is a technique of organizing information in a hierarchical form.

Java Inheritance provides a reusability mechanism in object-oriented programming for the users to reuse the existing code within the new applications.

It does this by allowing the programmer to build a relationship between a new class and an existing class and define a new code in terms of existing code. This relationship is known as parent-child relationship in java.

So, let’s understand the most important and powerful feature “Inheritance” of OOPs in more detail.

What is Inheritance in Java OOPs?


The technique of creating a new class by using an existing class functionality is called inheritance in Java. In other words, inheritance is a process by which a child class acquires all the properties and behaviors of the parent class.

The existing class is called parent class (a more general class) and the new class is called child class (a more specialized class). The child class inherits data and behavior from the parent class.

Let us take real-time examples to understand the concept of inheritance.

Realtime Example of Inheritance in Java

1. In the real world, a child inherits the features of its parents such as beauty of mother and intelligence of father as shown in the below figure.

Realtime example of inheritance in java

Inheritance represents the IS-A relationship, also known as a parent-child relationship.

What is Is-A relationship in Java?


Is-A relationship in java represents Inheritance. It is implemented in Java through keywords extends (for class inheritance) and implements (for interface implementation).

All the classes extends java.lang.object by default. This is a very good example of Is-A relationship in java. This means an object is the root class of all the classes in Java. Therefore, by default, every class is the subclass of java.lang.object.


So, every class acquires its properties from the object class. Hence, we can say that an object class is the superclass of every class.

For example:

class A {
  // statements
}
The Java compiler will treat the above code like this:
class A extends Object{
  // statements.
}

Let’s take one more example to understand Is-A relationship better. Look at the below figure to understand the Is-A relationship in java.

Is-A relationship in java

A car is a type of Vehicle, so inheritance hierarchy might begin from the Vehicle class as follows:

public class Vehicle { . . . . . . . . }
public class Car extends Vehicle { . . . . . }
public class Alto extends Car { . . . . . }

We can say the following terms in inheritance relationship. They are as follows:

  • Vehicle is the parent class (superclass) of Car.
  • Car is the child class (subclass) of Vehicle.
  • Car is the parent class of Alto.
  • Alto is the child class of Vehicle.
  • Car inherits from Vehicle.
  • Alto inherits from both Vehicle and Car.
  • Alto is derived from Car.
  • Car is derived from Vehicle.
  • Alto is derived from Vehicle.
  • Alto is a subtype of both Vehicle and Car.

In the terms of IS-A relationship, the following statements are true:

  • “Car extends Vehicle” means “Car IS-A Vehicle.”
  • “Alto extends Car” means “Alto IS-A Car.”

And we can also say that “Alto IS-A Vehicle”.

Figure b shows the inheritance hierarchy for Vehicle, Car, and Alto. The arrows move from the child class to the parent class. In other words, the arrow of class points toward that class from which it extends (inherits).

Important Terminology in Java Inheritance


1. Superclass/Parent class: The class from where a subclass inherits features is called superclass. It is also called base class or parent class in java.

2. Subclass/Child class: A class that inherits all the members (fields, methods, and nested classes) from other class is called subclass. It is also called a derived class, child class, or extended class.

A derived class extends its features by inheriting all the features of another class, called base class, and can also add its own features. The base class remains unchanged.

Creating Subclass in Java or Extending a class

A subclass can be created by using “extends” keyword. The syntax for defining and extending a class is as follows:

class subclassName extends superclassName
{
  // Variables of subclass
  // Methods of subclass
}

Where, class, and extends are two keywords.

The extends keyword indicates that you are deriving a new class (Derived class) from the existing class (Base class). In simple words, the extends keyword is used to make the relationship between two classes. Once the relationship is done, automatically, the code is reusable.

When we declare a derived class, no memory is allocated but memory is allocated when you create an object.


The subclass can inherit variables (data) and methods (behaviors) of the superclass if they are not declared as private. Consider the derivation of a new class from an existing class as shown in Fig.

Superclass and subclass in java

As shown in the above figure, the derived class acquires all the features of the base class (A and B) and adds its own feature (C). The arrow in the diagram expresses the concept of derivation.

The direction from derived class towards base class represents that the derived class has all the features of base class and not vice-versa.

Note: Inheritance is a compile-time mechanism. A parent class can have any number of derived class but a derived can have only one parent class. Therefore, Java does not support multiple inheritance.

3. Re-usability: A mechanism that facilitates to reuse fields and methods of the existing class into the new class is known as reusability.

When you create a new class, you can use the same fields and methods already defined in the previous class. This is called reusability.

In other words, inheritance allows an object to reuse the code of another object and also allows to add its own features as well.

How features of Superclass are inherited in Subclass?


Let’s take a simple example program to understand this concept of inheirtance. We will take the above diagram for example.

1. The base class is a superclass of derived class.
2. The derived class is a subclass of base class.
3. features() method of base class is inherited in the derived class.

Look at the following source code to understand better.

Program source code 1:

package inheritance; 
public class BaseClass
{    
  void features()
  {      
    System.out.println("Feature A");      
    System.out.println("Feature B");   
  } 
 } 
public class DerivedClass extends BaseClass
{   
  void ownFeature()
  {         
     System.out.println("Feature C");   
  } 
} 
public class InheritanceTest 
{   
 public static void main(String[] args) 
 {  
  // Create an object of the derived class.           
      DerivedClass d = new DerivedClass();  

 // Call features() method from the derived class using object reference variable d.             
       d.features(); // Call ownFeature() method using reference variable d.            
       d.ownFeature();     
  } 
}
Output:             
        Feature A             
        Feature B             
        Feature C

When an object of DerivedClass is created, it contains a copy of BaseClass within it. It means that there is a relationship between DerivedClass and BaseClass. This is the reason that the members of superclass are available to subclass.

In the above program, we did not create superclass object but still, a copy of it is available to the subclass. This is because the subclass object contains superclass object.

Inheritable Members of Classes and Interfaces in Java


In this section, we have listed inheritable members of classes and interfaces in table form below:

Types of Fields/Members Classes Interfaces
Instance variables Yes Not applicable
Static variables Yes Only constants
Abstract methods Yes Yes
Instance methods Yes Java 8, default methods
Static methods Yes Java 8, Inherited no, Accessible yes
Constructor No Not applicable
Initialization blocks No Not applicable

As you can notice in the following table, Java 8 has introduced a new feature that an interface can also contain two types of concrete methods, static and default.

We can inherit the default method from interfaces and access static method. This is a big change in Java 8.

Why do we need/use Inheritance in Java?


We use inheritance in java for the following reasons:

  • We can reuse the code from the base class.
  • Using inheritance, we can increase features of class or method by overriding.
  • Inheritance is used to use the existing features of class.
  • It is used to achieve runtime polymorphism i.e method overriding.
  • Using inheritance, we can organize the information in a hierarchal form.

Let’s take a program to understand the use of inheritance in Java. Consider the following program source code without using inheritance.

class A { 
 void m1(){ 
   . . . . 
 } 
} 
class B { 
 void m1(){ 
  . . . .  
 } 
 void m2(){ 
   . . . . 
 } 
} 
class C { 
 void m1(){ 
   . . . . 
  } 
 void m2(){ 
   . . . . 
  } 
 void m3(){ 
   . . . .  
  } 
 }

In the above program, class A contains one functionality i.e. one m1() method, class B contains two methods m1() and m2(), and class C contains three methods m1(), m2(), and m3(). So, what are the disadvantages of this code?

There are two disadvantages to this code.

1. First is code duplication.
2. Second is the length of the code.

Since in this code, the m1() method defined 3 times, m2() method defined two times. Here, the redundancy of code is code duplication. In the real-time project, code duplication is not allowed. Due to the duplication, the length of the code is also increased.

Therefore, we can reduce the length of the code by creating a relationship between two classes using the inheritance concept. but how?

We will use extends keyword to make a relationship between the two classes. Once the relationship is done, the code is automatically reusable.

Let us consider the program source code with inheritance.

class A { 
 void m1(){ 
    . . . . . 
   } 
 } 
class B extends A { 
 void m2(){ 
    . . . . . 
  } 
 } 
class C extends B { 
 void m3(){ 
    . . . . 
 } 
}

In this way, we can reduce the length of the code using inheritance concepts in Java applications. m1() method will automatically come in class B, m1() and m2() methods will come in class C. This is the main advantage of using inheritance in Java.

How is Inheritance implemented/achieved in Java?


Inheritance in Java can be implemented or achieved by using two keywords:

1. extends: extends is a keyword that is used for developing the inheritance between two classes and two interfaces. Note that a class always extends another class. An interface always extends another interface and can extend more than one interface.

2. implements: implements keyword is used for developing the inheritance between a class and interface. A class always implements the interface.

Role of Constructor in Java Inheritance


The role of constructor in inheritance is that the constructor in the superclass is responsible for building an object of superclass and the constructor of subclass builds an object of subclass.

When the constructor of a subclass is called during the object creation, by default, it calls the default constructor of superclass.

The superclass constructor can be called using keyword “super” from the subclass constructor. It must be the first statement in a constructor.

We can call other constructors of same class using this keyword but you cannot call a subclass constructor from the superclass constructor.

Advantage of Inheritance in Java


The advantages of inheritance in Java are as follows:

  • One of the main advantages is that you can minimize the length of duplicate code in an application by putting the common code in the superclass and sharing amongst several subclasses.
  • Due to reducing the length of code, redundancy of the application is also reduced.
  • Inheritance can also make application code more flexible to change because a class that inherits from the superclass, can be used interchangeably.

Let’s take a simple scenario to understand the advantage of using inheritance in java programming.

Scenario:

Suppose that a student has attributes like name, age, and location. This class exists for a long time. After some time, we need to add one attribute pan card of the student. So what will we have all the options?

1. The first option is that we can modify the class student.
2. The second option is we need to extend student class and add an attribute in the new class.

➲ The first option is the violation of principles of java ‘Java classes are not open for modifications’. So, we should not modify the existing one. This will increase unit testing to be done again for the existing class.

➲ The second option is without disturbing the existing class, we can add one variable to the other class by making a subclass. So only unit testing will need for the child class, not for the parent class.

Let’s look at the following program source code related to the above scenario.
Program source code 2:

package inheritance; 
public class Student 
{ 
  String name; 
  int age; 
  String location; 
 } 
public class Pancard extends Student 
{ 
  int pancard; 
}

Important Rules of Java Inheritance


1. We cannot assign a superclass to the subclass.
2. We cannot extend the final class.
3. A class cannot extend itself.
4. One class can extend only a single class.

5. We cannot extend a class having a private constructor but if we have private constructor as well as public constructor then we can extend superclass to subclass. In this case, the only public constructor will work.

6. If we assign subclass reference to superclass reference, it is called dynamic method dispatch in java.

7. Constructor, Static initialization block (SIB), and Instance initialization block (IIB) of the superclass cannot be inherited to its subclass but they are executed while creating an object of the subclass.

Let’s take an example program based on the constructor, static initialization block, and instance initialization block.

Program source code 3: 

package inheritance; 
public class A 
{ 
// Declare an instance variable and initialize value 10.      
  int a = 10;  
// Declare a default constructor.      
  A(){         
    System.out.println("Class A constructor");    
  } 
// Declare a static block.     
  static{         
    System.out.println("Class A SIB"); 
  } 
// Declare an instance block.      
   {          
     System.out.println("Class A IIB");      
   } 
  } 
public class B extends A{  
 int b = 20;
} 
public class Myclass { 
 public static void main(String[] args){ 
// Create an object of class B.         
  B obj = new B();        
   System.out.println("Value of a: " +obj.a);        
   System.out.println("Value of b: " +obj.b);  
  } 
 }
 Output:           
        Class A SIB           
        Class A IIB           
        Class A constructor           
        Value of a: 10           
        Value of b: 20

8. A static method of superclass is inherited to the subclass as a static member and non-static method is inherited as a non-static member only. Let’s understand it better by taking an example program.

Program source code 4:

package inheritance; 
public class A 
{ 
 // Declare an instance variable, static variable and initialize values.      
     int a = 10; // Non-static variable.      
     static int b = 30; // Static variable.   
     static void show()  
     {   
       System.out.println("Static method of class A");  
     }   
    void display() 
    {   
       System.out.println("Non-static method of class A");  
    } 
  } 
 public class B extends A 
 {   
   static int a = 20;      
    int b = 40;    
  void show()    
  {  
// Compile time error because the instance method cannot override the static method from class A.      
     System.out.println("Non-static method of class B");   
  }    
 static void display()   
  {   
// Compile time error because the static method cannot override instance method from class A.         
     System.out.println("Static method of class B");    
  } 
public static void main(String[] args)  
{ 
 // Create an object of class B.      
      B obj = new B();    
      System.out.println("Value of a: " +B.a);     
      System.out.println("Value of b: " +obj.b);     
        obj.show();    
        B.display();   
  } 
}
Output:            
        Value of a: 20            
        Value of b: 40           
        Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
        This instance method cannot override the static method from A

Hope that this tutorial has covered all basic topics based on inheritance in java with realtime example programs. I hope that you will have understood this topic.


Key Points to Remember

1. Building hierarchical relationships between related classes is called inheritance. It is also known as “IS-A” relationship.

2. It is the most important and powerful feature of OOPs concepts in Java that facilitates to reuse of code written in a class inside other classes.

3. It helps to organize information in a hierarchical form that is easy to understand.

4. There are five types of inheritance in Java. They are single-level, multilevel, hierarchical, multiple, and hybrid inheritance. The usable forms of inheritance are single inheritance, hierarchical inheritance, and multilevel inheritance.

5. Java does not support multiple inheritance through classes.

6. The main advantage of using inheritance is that it allows code to be reused.

Thanks for reading!!!
Next ⇒ Superclass and Subclass in Java⇐ PrevNext ⇒

Leave a Comment