Home » Inheritance in Java

Inheritance in Java

Inheritance in Java

In OOP, 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. It basically, helps in reusing the code and establish a relationship between different classes.

Inheritance is an object-oriented programming concept in which one class acquires the properties and behavior of another class. It represents a parent-child relationship between two classes. This parent-child relationship is also known as an IS-A relationship.

Inheritance Concept

Subclass

A subclass, also known as child class or derived class, is the class that inherits the properties and behaviors of another class. So, if A and B are two classes and if B class inherits A class, then the B class is called the subclass Superclass

A superclass, also known as parent class or base class, is the class whose properties and behaviors are inherited by the subclass. So, if A and B are two classes and if B class inherits A class, then A class is called the superclass.

Inheritance-types.png

Example

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

// Subclass
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat(); // Output: Animal is eating
        myDog.bark(); // Output: Dog is barking
    }
}
Java

Output

Animal is eating
Dog is barking
Java
  • When myDog.eat() is called, it invokes the eat() method inherited from the Animal superclass. So, it prints “Animal is eating”.
  • When myDog.bark() is called, it invokes the bark() method defined in the Dog subclass. So, it prints “Dog is barking”.

How to achieve/implement inheritance in Java?

Let us list out a few of the terms and keywords generally used in inheritance.

  • Subclass: The class that inherits the attributes and methods of another class.
  • Superclass: The class whose attributes and methods the subclass inherits.
  • Extends: The subclass uses the keyword to inherit the superclass.
  • Reusability: The methods and attributes of the superclass can be reused in the subclass because of inheritance, this is called reusability.

Example of Inheritance in Java

// Superclass
class Vehicle {
    private String brand;
    private int year;

    public Vehicle(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    public void drive() {
        System.out.println("Driving the " + year + " " + brand);
    }
}

// Subclass
class Car extends Vehicle {
    private int numDoors;

    public Car(String brand, int year, int numDoors) {
        super(brand, year); // Call superclass constructor
        this.numDoors = numDoors;
    }

    public void honk() {
        System.out.println("Honking the horn of the " + getYear() + " " + getBrand());
    }

    public int getNumDoors() {
        return numDoors;
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2020, 4);
        
        // Accessing superclass method
        myCar.drive(); // Output: Driving the 2020 Toyota
        
        // Accessing subclass methods and inherited methods
        myCar.honk(); // Output: Honking the horn of the 2020 Toyota
        System.out.println("Number of doors: " + myCar.getNumDoors()); // Output: Number of doors: 4
    }
}
Java

Output

Driving the 2020 Toyota
Honking the horn of the 2020 Toyota
Number of doors: 4
Java
  • myCar.drive() invokes the drive() method inherited from the Vehicle superclass, which prints “Driving the 2020 Toyota”.
  • myCar.honk() invokes the honk() method defined in the Car subclass, which prints “Honking the horn of the 2020 Toyota”.
  • System.out.println("Number of doors: " + myCar.getNumDoors()) prints the number of doors of the car, which is 4.

Types of Inheritance in Java

  1. Single Inheritance
  2. Multi-level Inheritance
  3. Hierarchical Inheritance
  4. Hybrid Inheritance

1. Single Inheritance

Single inheritance in Java refers to the inheritance relationship where a subclass extends only one superclass. Here’s an example demonstrating single inheritance.

Example

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

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

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        
        // Accessing superclass method
        myDog.eat(); // Output: Animal is eating
        
        // Accessing subclass method
        myDog.bark(); // Output: Dog is barking
    }
}
Java

Output

Animal is eating
Dog is barking
Java

2. Multi-level Inheritance

Multi-level inheritance in Java refers to a scenario where a class inherits properties and behaviors from another class, which in turn inherits from another class. This creates a hierarchical structure of classes where each class inherits from the one above it.

Example

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

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

// Sub-child class inheriting from Dog
class Labrador extends Dog {
    void display() {
        System.out.println("Labrador is a type of Dog");
    }
}

public class Main {
    public static void main(String[] args) {
        Labrador labrador = new Labrador();
        labrador.eat();   // Inherited from Animal
        labrador.bark();  // Inherited from Dog
        labrador.display();  // Defined in Labrador class
    }
}
Java

Output

Animal is eating
Dog is barking
Labrador is a type of Dog
Java

3. Hierarchical Inheritance

Hierarchical inheritance in Java refers to a scenario where multiple classes inherit properties and behaviors from a single parent class. In this inheritance structure, there is one parent class and multiple child classes that inherit from it.

Example

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

// Child class 1 inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

// Child class 2 inheriting from Animal
class Cat extends Animal {
    void meow() {
        System.out.println("Cat is meowing");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();   // Inherited from Animal
        dog.bark();  // Defined in Dog class

        Cat cat = new Cat();
        cat.eat();   // Inherited from Animal
        cat.meow();  // Defined in Cat class
    }
}
Java

Output

Animal is eating
Dog is barking
Animal is eating
Cat is meowing
Java

4. Hybrid Inheritance

Hybrid inheritance in Java refers to a combination of multiple inheritance and hierarchical inheritance. In hybrid inheritance, a class is derived from two or more classes, and these derived classes can further have their own subclasses. Java doesn’t support multiple inheritance directly due to the diamond problem, but hybrid inheritance can be achieved by combining hierarchical inheritance and interface implementation.

Example

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

// Child class 1 inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

// Child class 2 inheriting from Animal
class Cat extends Animal {
    void meow() {
        System.out.println("Cat is meowing");
    }
}

// Interface defining behavior for domestic animals
interface Domestic {
    void play();
}

// Sub-interface for specific type of domestic animals
interface DogBehavior extends Domestic {
    void guard();
}

// Class implementing Domestic and DogBehavior interfaces
class DomesticDog implements DogBehavior {
    public void play() {
        System.out.println("Domestic dog is playing");
    }

    public void guard() {
        System.out.println("Domestic dog is guarding");
    }
}

public class Main {
    public static void main(String[] args) {
        DomesticDog dog = new DomesticDog();
        dog.play();    // Defined in Domestic interface
        dog.guard();   // Defined in DogBehavior interface
    }
}
Java

Output

Domestic dog is playing
Domestic dog is guarding
Java

Diamond Problem In Java

The diamond problem, also known as the deadly diamond of death, is a common issue in multiple inheritance systems like C++ and some implementations of Java interfaces. It occurs when a class inherits from two classes that have a common ancestor.

Consider the following scenario:

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

// Child class 1 inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

// Child class 2 inheriting from Animal
class Cat extends Animal {
    void meow() {
        System.out.println("Cat is meowing");
    }
}

// Hybrid class inheriting from both Dog and Cat
class Hybrid extends Dog, Cat { // Error: Multiple inheritance not supported in Java
    void hybridBehavior() {
        System.out.println("Hybrid behavior");
    }
}
Java

In this example, the class Hybrid attempts to inherit from both Dog and Cat classes, which in turn inherit from the Animal class. This would lead to a diamond-shaped inheritance hierarchy:

    Animal
   /     
  Dog   Cat
        /
   Hybrid

Java

Note: The above program is just for understanding that multiple inheritance of classes is invalid in Java.

 Advantages Of Inheritance in Java

Here are some advantages of inheritance in Java presented in bullet points:

  • Code Reusability: Inheritance allows classes to inherit attributes and methods from another class, promoting code reuse by avoiding redundant code.
  • Maintenance: Changes made to a base class are automatically reflected in all derived classes, reducing maintenance efforts and ensuring consistency throughout the codebase.
  • Extensibility: Derived classes can extend the functionality of the base class by adding new methods and attributes, providing a way to build upon existing code without modifying it directly.
  • Polymorphism: Inheritance facilitates polymorphism, where objects of derived classes can be treated as objects of the base class, enabling dynamic method invocation and flexibility in programming.
  • Organization: Inheritance promotes a hierarchical structure, allowing for better organization and understanding of the relationships between classes.
  • Encapsulation: Inheritance supports encapsulation by allowing the base class to hide its implementation details while providing an interface for derived classes to access and modify its behavior through inheritance.
  • Efficiency: In some cases, inheritance can improve code performance by reducing redundancy and promoting efficient code reuse.
  • Promotes Code Maintainability: Inheritance promotes modular programming, making code easier to understand, debug, and maintain by breaking it into smaller, more manageable components.
  • Facilitates Design Patterns: Inheritance is a key concept in various design patterns such as Factory Method, Template Method, and Strategy Pattern, allowing developers to implement these patterns effectively.
  • Facilitates Polymorphism: Inheritance enables polymorphism, which allows objects of different derived classes to be treated uniformly, providing flexibility and extensibility in the design and implementation of Java applications.

These advantages collectively contribute to the development of more efficient, maintainable, and scalable Java applications.

Conclusion

Java inheritance is a powerful mechanism that allows classes to inherit attributes and behaviors from other classes. It promotes code reuse, extensibility, and polymorphism, facilitating the development of efficient, maintainable, and scalable Java applications. By enabling the creation of hierarchical relationships between classes, inheritance enhances code organization, promotes modular programming, and supports the implementation of various design patterns. Overall, Java inheritance plays a fundamental role in object-oriented programming, contributing to the development of robust and flexible software solutions.

Frequently Asked Questions

What is Java inheritance?

Java inheritance is a mechanism where a new class, known as the derived class or subclass, is created by inheriting attributes and methods from an existing class, known as the base class or superclass.

How is inheritance achieved in Java?

In Java, inheritance is achieved using the extends keyword to indicate that one class inherits from another. The subclass inherits all non-private members (fields and methods) of the superclass.

What are the types of inheritance supported in Java?

Java supports single inheritance, where a class can inherit from only one superclass, and multiple interfaces can be implemented. It does not support multiple inheritance of classes to avoid the diamond problem.

What is the purpose of using inheritance in Java?

The primary purpose of inheritance in Java is to promote code reuse, extensibility, and polymorphism. It allows developers to create new classes based on existing ones, thereby reducing redundancy and promoting modular design.

What is the super keyword in Java?

The super keyword in Java is used to access members of the superclass from within the subclass. It can be used to invoke the superclass constructor or methods, as well as to differentiate between superclass and subclass members with the same name.