DEV Community

PRIYA K
PRIYA K

Posted on • Edited on

Inheritance in java

Inheritance in Java with Examples

Inheritance in Java is a concept that acquires the properties from one class to other classes; it's a parent-child relationship.

mygreatlearning.com

Inheritance in Java - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org





Inheritance in Java: Types and Working with Examples | igmGuru

Understand Inheritance in Java, the core principle of Java OOP that allows a class to acquire the properties (fields) and behaviors (methods) of another class.

favicon igmguru.com


Types of Inheritance in Java with Example - Hero Vired

Get comprehensive guide on types of Inheritance in Java with example. Check the details about single, multiple, multilevel, Hybrid and hierarchical inheritance here.

favicon herovired.com

Java - Inheritance

In Java programming, the inheritance is an important of concept of Java OOPs. Inheritance is a process where one class acquires the properties (methods and attributes) of another.

favicon tutorialspoint.com


  • One Of the object-oriented With the use of inheritance, the information is made manageable in a hierarchical order.
  • Allows one class(subclass or child) to acquire or inherit fields and methods of another class(superclass or parent )
  • field => Global variable
    static and non-static variables.

  • Inheritance enables derivative classes to receive the features of base classes.
    establishes a hierarchical relationship between classes.
    Inheritance is used to create a new class that is a type of an existing class. It helps in extending the functionality of a class without modifying it, thereby adhering to the Open/Closed Principle of software design.

Important Points for Inheritance

  • Excepting Object, which has no superclass. Absence of any other explicit superclass, every class is implicitly a subclass of Object.

  • Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object.

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

The Java Platform Class Hierarchy

The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes

All Classes in the Java Platform are Descendants of Object

At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.

What You Can Do in a Subclass

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

In OOPS, computer programs are designed in such a way where everything is an object that interacts with one another. Inheritance is an integral part of Java OOPS, which lets the properties of one class to be inherited by the other.

  1. Parent class ( Super or Base class )

  2. Child class ( Subclass or Derived class )

Benefits of Using Inheritance in Java
Code Reusability: Inheritance allows subclasses to reuse code from the parent class.
code reusability by promoting IS A relationship

  • Creating a new class from the existing class
  • It helps in code reuse and establishes a relationship between classes.(parent class or child class)
  • While Multiple and Hybrid inheritance are not supported using classes, they can be achieved using Interfaces
    Promotes code reuse
    Simplifies maintenance and debugging
    Enables polymorphic programming
    Reflects real-world hierarchical relationships
    Encourages extension rather than modification

    Maintainability: Changes in the superclass reflect automatically in the subclasses, making maintenance easier.

    Polymorphism: Allows the method of a subclass to be invoked, even when using the superclass reference.
    Extensibility: New classes can extend existing ones without modifying the original code (open/closed principle)

Avoid Deep Inheritance Hierarchies: Keep inheritance hierarchies shallow to maintain simplicity and reduce complexity.

Prefer Composition Over Inheritance: Consider using composition (has-a relationship) instead of inheritance when appropriate, as it offers more flexibility.

Use @override Annotation: Always use the @override annotation when overriding methods to improve code readability and prevent errors.

Access Control: Use the protected access modifier for superclass members that should be accessible in subclasses but not to the outside world.

Common Inheritance Pitfalls in Java
Tight Coupling: Subclasses can become tightly coupled to their superclasses, making changes difficult.

Overridden Method Confusion: If methods are overridden incorrectly, it may lead to unexpected results.

Lack of Flexibility in Inheriting Multiple Classes: Java doesn't allow multiple inheritance directly, which can lead to limitations when modeling complex relationships.
Enter fullscreen mode Exit fullscreen mode

Class
Blueprint from which objects are created
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.

Reusablity: As the name specifies, reusablity is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Super class (Parent):
The existing class whose features are inherited.
the class being inherited from
Class whose properties are inherited
Super class is the class from where a subclass inherits the features. It is also called a base class or a parent class.
A class whose properties and methods are inherited by another class.
the super keyword is used to call the method of the parent class from the method of the child class.

class Animal {

  // method in the superclass
  public void eat() {
    System.out.println("I can eat");
  }
}

// Dog inherits Animal
class Dog extends Animal {

  // overriding the eat() method
  @Override
  public void eat() {

    // call method of superclass
    super.eat();
    System.out.println("I eat dog food");
  }

  // new method in subclass
  public void bark() {
    System.out.println("I can bark");
  }
}

class Main {
  public static void main(String[] args) {

    // create an object of the subclass
    Dog labrador = new Dog();

    // call the eat() method
    labrador.eat();
    labrador.bark();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

I can eat
I eat dog food
I can bark

use the super keyword to call the constructor of the superclass from the constructor of the subclass

protected Members in Inheritance

In Java, if a class includes protected fields and methods, then these fields and methods are accessible from the subclass of the class.

class Animal {
  protected String name;

  protected void display() {
    System.out.println("I am an animal.");
  }
}

class Dog extends Animal {

  public void getInfo() {
    System.out.println("My name is " + name);
  }
}

class Main {
  public static void main(String[] args) {

    // create an object of the subclass
    Dog labrador = new Dog();

    // access protected field and method
    // using the object of subclass
    labrador.name = "Rocky";
    labrador.display();

    labrador.getInfo();
  }
}
Enter fullscreen mode Exit fullscreen mode

Subclass (Child):
The new class that inherits features and can add its own unique fields or methods.
It is also called a derived class, extended class, or child class.
the class that inherits from another class
A subclass can reuse the fields and methods of the parent class without rewriting the code
A subclass can add its own fields and methods or modify existing ones to extend functionality.
A class that inherits the properties and methods from a superclass.

Subclass and Superclass:
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.

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.

extends Keyword:
The specific keyword used to perform inheritance between classes.
In Java, inheritance is implemented using the extends keyword.
The extends keyword in Java code enables inheritance through which child classes automatically obtain attributes and behaviors from parent classes.
Used by the subclass to inherit from the superclass.
The word "extends" means to extend functionalities i.e., the extensibility of the features.

Implements keyword
how the implements keyword is used to get the IS-A relationship.

Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class.

Example

public interface Animal {
}
public class Mammal implements Animal {
}
public class Dog extends Mammal {
}
Enter fullscreen mode Exit fullscreen mode

Java Inheritance: The instanceof Keyword

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal.

Example

interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal {
   public static void main(String args[]) {
      Mammal m = new Mammal();
      Dog d = new Dog();
      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}
Enter fullscreen mode Exit fullscreen mode

Output
true
true
true

HAS-A relationship
This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Example
public class Vehicle{}
public class Speed{}

public class Van extends Vehicle {
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

super Keyword:
Used inside a subclass to refer to immediate parent class members, such as variables, methods, or constructors.
The super keyword is similar to this keyword.
It is used to differentiate the members of superclass from the members of subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.

Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword.

Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword.

Syntax

    class Parent {
        // fields and methods
    }
    class Child extends Parent {

        // additional fields and methods

    }
Enter fullscreen mode Exit fullscreen mode

Example

// Parent class
class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

// Child class
class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();   // inherited from Animal
        d.bark();  // defined in Dog
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal {
}

public class Mammal extends Animal {
}

public class Reptile extends Animal {
}

public class Dog extends Mammal {
}
Enter fullscreen mode Exit fullscreen mode

Now, based on the above example, in Object-Oriented terms, the following are true −

Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Enter fullscreen mode Exit fullscreen mode

Now, if we consider the IS-A relationship, we can say −

Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
Enter fullscreen mode Exit fullscreen mode

Types Of Inheritance
1. Single Inheritance
a single subclass extends from a single superclass
A sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
A subclass inherits from exactly one superclass.
It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
This is the most basic form of inheritance.
mirroring straightforward “is-a” relationships.
Use case
Extending a base class with new specialised behaviour
Structure: Class B (child) extends Class A (parent). Class B gains all non-private fields and methods of Class A.
A subclass inherits directly from a single superclass.

Single Inheritance Example
“Student” class extends “Person” class.
Person defines name and age.
Student inherits these fields and adds roll number, study method, etc.

Syntax

class Parent {
    // properties and methods
}

class Child extends Parent {
    // additional properties and methods
}
Enter fullscreen mode Exit fullscreen mode

Example

class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();

        d.eat();   // Inherited from Animal
        d.bark();  // Defined in Dog
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Animal is eating
Dog is barking

Advantages of Single Inheritance
Code Re-usability – Child class can reuse parent class methods.
Reduces Code Duplication – No need to write the same code again.
Easy Maintenance – Changes in the parent class are reflected in child classes.
Supports Method Overriding – Enables runtime polymorphism.

2. Multilevel Inheritance
a subclass extends from a superclass and then the same subclass acts as a superclass for another class.
Key Point: Multilevel inheritance enables progressive generalization—adding features and specializations layer by layer.
Levels
Multilevel inheritance involves multiple base classes.
3 or more
A derived class will be inheriting a base class and as well as the derived class also acts as the base class for other classes.
there is a chain of inheritance.
A subclass inherits from another subclass, forming a chain.
a class is derived from another class, which is also a subclass of another class.
A subclass extends an intermediate class, which in turn extends a base class.
forming a linear chain of inheritance
Key rule
Each class inherits all accessible members from all ancestors up the chain
Use case
Progressively specialised class hierarchies (Vehicle → Car → ElectricCar)
Key Point: Multilevel inheritance enables progressive generalization—adding features and specializations layer by layer.

Multilevel inheritance in java creates a chain of inheritance across three or more levels. Class C inherits from Class B, which itself inherits from Class A. This creates a linear ancestor hierarchy – each class adds to the behaviour of the one above it.

Grandparent → Parent → Child
Structure: Class A → Class B → Class C

Multilevel Inheritance Example
“SportsCar” extends “Car”, which extends “Vehicle”.
Vehicle: fields for speed, fuel
Car: adds model, manufacturer
SportsCar: adds turbo mode, racing features

Syntax

class A {
    // properties and methods
}

class B extends A {
    // inherits A
}

class C extends B {
    // inherits B and A
}
Enter fullscreen mode Exit fullscreen mode

Example

// Parent class
class Animal {
void eat() {
        System.out.println("This animal eats food.");
    }
}

// Child class
class Dog extends Animal {
void bark() {
        System.out.println("The dog barks.");
    }
}

class Puppy extends Dog{
void weep(){
        System.out.println("The puppy weeps.");
    }
}

// Main class
public class MultiLevelInheritance {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();   // inherited from Animal
        p.bark();  // defined in Dog
        p.weep();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Animal is eating
Dog is barking
Puppy is weeping

3. Hierarchical Inheritance
multiple subclasses extend from a single superclass
Multiple subclasses inherit from the same superclass (siblings).
more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.
Multiple subclasses inherit from a single parent class or superclasses.
When two or more classes inherits a single class, it is known as hierarchical inheritance.
It creates a tree-like structure branching outwards.
One Parent → Multiple Children
Multiple distinct child classes all extend the same single parent class. 
one class serves as a superclass for more than a one subclass
Key Point: Useful for modeling “family trees” where all subclasses share a common set of features but each adds its own.
Key Point: Useful for modeling “family trees” where all subclasses share a common set of features but each adds its own.

Hierarchical Inheritance Example
“Manager”, “Engineer”, and “Intern” all extend “Employee”.
All share base salary, employee ID, etc.
Each adds its own departmental or role-specific fields/methods.

Parent classes
1

Child classes
2 or more

Structure
Fan-out – one parent, multiple children

Java support
Full

Use case
Shared base behaviour with specialised subclass implementations
This is useful when you have several specialized classes that share common base functionality

Hierarchical inheritance in java occurs when multiple child classes inherit from a single parent class. All subclasses share the common behaviour defined in the parent, while each can also add its own specialised methods. This creates a fan-out structure – one parent, many children.

shared superclass.
Structure: Class A → Class B and Class A → Class C

Hierarchical inheritance is a type of inheritance in which multiple child classes inherit from a single parent class.

In other words:
One Parent Class → Many Child Classes

Syntax

class Parent {
    // properties and methods
}

class Child1 extends Parent {
    // inherits Parent
}

class Child2 extends Parent {
    // inherits Parent
}
Enter fullscreen mode Exit fullscreen mode

Example

// Parent class
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

// Child 1
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

// Child 2
class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows");
    }
}

// Main class
public class HierarchicalInheritance {
    public static void main(String[] args) {

        Dog d = new Dog();
        d.eat();
        d.bark();

        Cat c = new Cat();
        c.eat();
        c.meow();
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes.
One class inherits from more than one parent class. Not supported for classes in Java to avoid ambiguity (the Diamond Problem).

Note: that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces.  A class can implement multiple interfaces.
Enter fullscreen mode Exit fullscreen mode
// Interface 1
interface Animal {
    void eat();
}

// Interface 2
interface Pet {
    void play();
}

// Class implementing both interfaces
class Dog implements Animal, Pet {

    public void eat() {
        System.out.println("Dog eats food");
    }

    public void play() {
        System.out.println("Dog plays");
    }

    void bark() {
        System.out.println("Dog barks");
    }
}

// Main class
public class MultipleInheritance {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.play();
        d.bark();
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
A combination of two or more types of inheritance.

// Base class
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

// Interface 1
interface Pet {
    void play();
}

// Interface 2
interface Guard {
    void protect();
}

// Hybrid: extends class + implements interfaces
class Dog extends Animal implements Pet, Guard {

    public void play() {
        System.out.println("Dog plays");
    }

    public void protect() {
        System.out.println("Dog protects house");
    }

    void bark() {
        System.out.println("Dog barks");
    }
}

// Main class
public class HybridInheritance {
    public static void main(String[] args) {
        Dog d = new Dog();

        d.eat();     // from Animal
        d.play();    // from Pet
        d.protect(); // from Guard
        d.bark();    // own method
    }
}
Enter fullscreen mode Exit fullscreen mode

6.Constructor Inheritance in Java
constructors are not inherited by subclasses, but they can be invoked using super(). The constructor of the superclass is called before the subclass's constructor.

Why Use Inheritance?
Code Reusability: Subclasses reuse the parent class's code without redefining it.
Method Overriding: Subclasses can provide specific implementations for methods defined in the parent, enabling Runtime Polymorphism.
Logical Organization: It helps organize classes into a clear, tree-like hierarchy that reflects real-world relationships

Important Rules & Constraints
Access Control: Subclasses do not inherit private members of the superclass. They inherit public and protected members.
Constructors: These are not inherited, but a subclass must call the superclass constructor (implicitly or via super()) as the first statement in its own constructor.
Final Keyword: A class declared as final cannot be inherited, and a method declared as final cannot be overridden.Implicit Parent: If no superclass is specified, every Java class implicitly inherits from the Object class.

The final Keyword
If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}
Enter fullscreen mode Exit fullscreen mode

Output

The output will be something like this:
Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error)

Frequently Asked Questions

  1. Why is multiple inheritance (of classes) not supported in Java?

Java does not support multiple inheritance with classes to avoid the diamond problem, where ambiguity arises if two parent classes have the same method. This ensures cleaner, less error-prone code.

  1. How can we achieve multiple inheritance in Java?

In Java, multiple inheritance is achieved through interfaces. A class can implement multiple interfaces, inheriting methods from each without ambiguity.

Also Read: Difference between abstract classes and interfaces in Java

  1. Can constructors be inherited in Java?

Constructors are not inherited in Java, but a subclass can call the constructor of its superclass using the super() keyword to initialize the parent class.

A very important fact to remember is that Java does not support multiple and hybrid inheritances. This means that a class cannot extend more than one class. Therefore following is illegal −

However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance.

Top comments (0)