Inheritance in Java with Examples

Inheritance is a powerful object-oriented programming feature offered by Java. It is one of the four main pillars (core concepts) of OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction.

Inheritance is a technique of organizing and structuring information in a hierarchical form. This powerful feature allows to one class to inherit the properties (fields) and behaviours (methods) of another class.

Inheritance provides a strong reusability mechanism in Java that enables the programmers to reuse the existing code in the new applications. As a result, code duplication is reduced and program maintainability increases.

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 commonly known as parent-child relationship or superclass-subclass relationship in Java.

In this tutorial, we will understand the basics of inheritance in Java along with real-time example programs, Is-A relationship, creating superclass and subclass, uses, and advantages.

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 understand the meaning or definition of inheritance with the help of a real-time example.

Realtime Example of Inheritance


In the real world, a child inherits certain features or characteristics of its parents, such as mother’s beauty and the father’s intelligence, 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 using:

  • the extends keyword for class inheritance, and
  • the implements keyword for interface implementation.

IS-A Relationship Example

All the classes in Java extends the class java.lang.object by default. This is one of the best example of an IS-A relationship in Java. This means Object is the root class of all the classes in Java.

By default, every class is the subclass of Object either directly or indirectly. Therefore, every class inherits methods of the Object class. Hence, we can say that Object class is the superclass of every class. When you write:

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

Thus, class A IS-A Object.

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 another 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.

3. Reusability

A mechanism that allows a new class to reuse fields and methods of the existing class is known as reusability. This is one of the major advantages of inheritance in Java.

When you create a new class, you can use the fields and methods already defined in the existing (parent) class without rewriting the code. 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 additional features as well.

Syntax to Create Subclass in Java (Extending a Class)


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

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

In the above syntax,

  • We have created a subclass class that inherits from another class by extend clause in the class header. Here, class and extends are two keywords in Java.
  • 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, the subclass can automatically reuse the code of the superclass.

Memory Allocation

When you declare a derived class, no memory is allocated, but memory is allocated only when you create an object of the subclass or superclass.

Members Inheritance Rules

  • The subclass can inherit variables (data) and methods (behaviors) of the superclass if they are not declared as private.
  • Protected and public members are accessible.
  • The default members are accessible only if both classes are in the same package.

Consider the derivation of a new class from an existing class, as shown in Fig.

Superclass and subclass relationship 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 the derived class towards base class represents that the derived class has all the features of the base class and not vice versa.

Note:
  • Inheritance in Java is a compile-time mechanism, meaning the inheritance structure (superclass–subclass relationship) is checked and validated at compile time.
  • However, method overriding within inheritance is resolved at runtime through dynamic binding.
  • 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.

How Features of Superclass are Inherited in Subclass?


Let’s take a simple example program to understand how features of superclass are inherited in the subclass through inheritance in Java. Consider the above diagram for example.

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


Look at the following example code to understand better.

package inheritance; 
// Creating a superclass.
class BaseClass
{    
  void features()
  {      
     System.out.println("Feature A");      
     System.out.println("Feature B");   
  } 
 } 
// Creating a subclass.
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

In this example,

  • When an object of DerivedClass is created, it automatically includes all the inherited fields and methods of BaseClass.
  • This means the DerivedClass object contains the state and behavior defined in the BaseClass. This is the reason that the members of superclass are available to subclass.
  • In the above example, we did not explicitly create an object of the superclass. However, the subclass object still has access to the superclass members because the subclass object internally includes the superclass part during object creation.
  • This happens because the constructor of the superclass is invoked automatically before the subclass constructor.

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/MembersClassesInterfaces
Instance variablesYesNot applicable
Static variablesYesOnly constants
Abstract methodsYesYes
Instance methodsYesJava 8, default methods
Static methodsYesJava 8, Inherited no, Accessible yes
ConstructorNoNot applicable
Initialization blocksNoNot 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 Use Inheritance in Java?


We use inheritance in Java for the following reasons:

  • We can reuse the fields and methods of an existing (base) class without rewriting the code.
  • By using inheritance, we can increase features of class by overriding its methods in the subclass.
  • Inheritance allows us to use the existing features of a class and extend them as needed.
  • It is used to achieve runtime polymorphism i.e. method overriding.
  • Using inheritance, we can organize related classes in a hierarchical structure, improving code clarity, structure, and maintainability.

Example: Without Inheritance vs With Inheritance

Consider the following example 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.

  • First is code duplication.
  • Second is the length of the code.

In the above code, the m1() method is defined 3 times, and m2() method is 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 feature. But how?

With Inheritance

By using extends keyword, we will make a relationship between the two classes. Once the relationship is done, the code is automatically reusable. Look at the below example code where we have used inheritance feature.

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:

  • The keyword extends 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:

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

Role of Constructors in Inheritance


In inheritance, the constructor of the superclass is responsible for initializing the superclass part of an object, and the constructor of the subclass initializes the subclass part.

When a subclass constructor is executed during object creation, it automatically calls the superclass constructor first. If no explicit call is made, the compiler inserts a call to the default constructor of the superclass.

You can explicitly call a specific superclass constructor using the super keyword. The super() call must always be the first statement inside the subclass constructor.

You can also call another constructor within the same class using the this keyword, but you cannot call a subclass constructor from a superclass constructor. The constructor chain always moves from parent to child, not the other way around.

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?

  • The first option is that we can modify the class student.
  • 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.

Look at the following example code related to the above scenario.

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

Important Rules of Java Inheritance


There are the following rules of using inheritance in Java:

  • You cannot assign a superclass to the subclass.
  • You cannot extend the final class because a class declared with the final keyword cannot be inherited.
  • A class cannot extend itself.
  • A class can extend only one class.
  • You cannot extend a class that has only a private constructor. However, if the class has a private constructor and at least one public or protected constructor, it can be extended.
  • If you assign a subclass object to a superclass reference, it is called upcasting in Java.
  • Constructor, Static initialization block (SIB), and Instance initialization block (IIB) of the superclass are not inherited by the subclass. However, they are executed while creating an object of the subclass.
  • A static method of a superclass is accessible from a subclass, but it is not inherited in the same way as instance methods. Static methods are hidden, not overridden.

Let’s take examples based on the rules of inheritance in Java.

Example 1:

package inheritance; 
class A 
{ 
// Declare an instance variable and initialize value 10.      
   int a = 10;  
// Declare a 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");      
   } 
  } 
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

 Example 2:

package inheritance; 
class A 
{ 
// Declare an instance variable, static variable and initialize values.      
   int a = 10; // non-static variable.      
   static int b = 30; // static variable.   
  
// Static method.   
   static void show()  
   {   
      System.out.println("Static method of class A");  
   } 
// Instance method.  
   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()    
   {  
  // This statement will generate a 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()   
   {   
  // This statement will generate a 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
Key Points to Remember:
  • Building hierarchical relationships between related classes is called inheritance. It is also known as “IS-A” relationship.
  • 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.
  • It helps to organize information in a hierarchical form that is easy to understand.
  • There are five types of inheritance in Java: single-level, multilevel, hierarchical, multiple, and hybrid inheritance.
  • The usable forms of inheritance are single inheritance, hierarchical inheritance, and multilevel inheritance.
  • Java does not support multiple inheritance through classes.
  • The main advantage of using inheritance is that it allows code to be reused.
DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the founder of Scientech Easy and a passionate coding educator with 8 years of professional experience in Java, Python, web development, and core computer science subjects. With expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He consistently publishes in-depth tutorials, practical coding examples, and valuable learning resources for beginners as well as working professionals. Each article is carefully researched and reviewed to ensure accuracy, quality, and real-world relevance.