zaro

What types of inheritance does Java support?

Published in Java Inheritance 5 mins read

Java, a widely-used object-oriented programming language, supports four primary types of inheritance: single, multilevel, hierarchical, and hybrid. This fundamental concept allows classes to inherit attributes and behaviors from other classes, promoting code reusability and establishing "IS-A" relationships between objects.

Understanding Inheritance in Java

Inheritance is a core principle of Object-Oriented Programming (OOP) that enables a new class (subclass or child class) to derive properties and functionalities from an existing class (superclass or parent class). This mechanism helps in creating a hierarchy among classes, reducing code duplication, and improving the maintainability of applications. In Java, the extends keyword is used to establish an inheritance relationship between classes.

The Four Types of Inheritance in Java

Java supports specific patterns of class inheritance to ensure simplicity and avoid complex scenarios like the "Diamond Problem."

1. Single Inheritance

Single inheritance is the simplest form of inheritance where a class inherits from only one superclass. This creates a straightforward parent-child relationship.

  • Description: One subclass extends one superclass.

  • Example:

    class Animal {
        void eat() {
            System.out.println("Animal eats food.");
        }
    }
    
    class Dog extends Animal { // Dog inherits from Animal
        void bark() {
            System.out.println("Dog barks.");
        }
    }
  • Practical Insight: It's commonly used for direct specialization, like a Car extending a Vehicle.

2. Multilevel Inheritance

In multilevel inheritance, a class inherits from another class, which in turn inherits from yet another class. This forms a chain of inheritance, where there's an intermediate superclass.

  • Description: A subclass inherits from a class that already inherits from another class, forming a chain (A -> B -> C).

  • Example:

    class Animal { // Grandparent
        void eat() {
            System.out.println("Animal eats food.");
        }
    }
    
    class Dog extends Animal { // Parent
        void bark() {
            System.out.println("Dog barks.");
        }
    }
    
    class BabyDog extends Dog { // Child
        void weep() {
            System.out.println("BabyDog weeps.");
        }
    }
  • Practical Insight: Useful for building progressive layers of abstraction and specialization, such as SportsCar extending Car, which extends Vehicle.

3. Hierarchical Inheritance

Hierarchical inheritance occurs when multiple subclasses inherit from a single superclass. This means one parent class has several child classes.

  • Description: One superclass is inherited by multiple subclasses.

  • Example:

    class Animal {
        void eat() {
            System.out.println("Animal eats food.");
        }
    }
    
    class Dog extends Animal { // Dog inherits from Animal
        void bark() {
            System.out.println("Dog barks.");
        }
    }
    
    class Cat extends Animal { // Cat also inherits from Animal
        void meow() {
            System.out.println("Cat meows.");
        }
    }
  • Practical Insight: Ideal for defining a common base for a group of related but distinct entities, like SavingsAccount and CheckingAccount both inheriting from BankAccount.

4. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance (e.g., combining single and hierarchical inheritance). While Java does not support multiple inheritance directly with classes (to prevent complexity), hybrid patterns are achievable through a combination of class inheritance and interface implementation.

  • Description: A mix of two or more of the other inheritance types (single, multilevel, hierarchical). In Java, this often involves using interfaces to overcome the lack of multiple class inheritance.

  • Conceptual Example:
    Imagine a scenario where:

    • Vehicle is a superclass.
    • Car and Truck inherit from Vehicle (Hierarchical).
    • SportsCar inherits from Car (Multilevel from Vehicle to Car to SportsCar).

    This structure, combining hierarchical and multilevel inheritance patterns, represents a hybrid inheritance model in Java.

Why Java Does Not Support Multiple Inheritance (with Classes)

Java intentionally does not support multiple inheritance with classes. This design choice was made to simplify the language and avoid complex issues, most notably the "Diamond Problem." The Diamond Problem arises when a class inherits from two parent classes, and those parent classes both inherit from a common grandparent class. If there's a method defined in the grandparent and overridden differently in both parent classes, the child class wouldn't know which overridden method to inherit.

Achieving Multiple Inheritance-like Behavior with Interfaces

While multiple inheritance is not supported with classes, Java addresses the need for a class to acquire behavior from multiple sources through interfaces. A class can implement multiple interfaces, thereby inheriting method signatures and default methods from all of them. This allows Java to achieve polymorphism and code reusability similar to multiple inheritance, but without the complexities of state inheritance.

For example:

interface Swimmer {
    void swim();
}

interface Runner {
    void run();
}

class Athlete implements Swimmer, Runner { // Implements multiple interfaces
    public void swim() {
        System.out.println("Athlete is swimming.");
    }
    public void run() {
        System.out.println("Athlete is running.");
    }
}

Key Concepts in Java Inheritance

Beyond the types, understanding these core concepts is crucial for working with inheritance in Java:

  • extends Keyword: Used to establish the inheritance relationship between a subclass and a superclass.
  • super Keyword: Used to refer to the immediate parent class object. It can be used to call parent class constructors and methods.
  • Method Overriding: A subclass provides its own specific implementation of a method that is already provided by its superclass.
  • Constructor Chaining: When a subclass object is created, the constructor of the superclass is automatically invoked (implicitly or explicitly via super()).
  • IS-A Relationship: Inheritance defines an "IS-A" relationship, meaning a subclass "is a type of" its superclass (e.g., a Dog IS-A Animal).

For more in-depth information on Java inheritance, you can refer to the official Oracle Java Documentation.

Overview of Java Inheritance Types

Inheritance Type Description Example Analogy
Single A class inherits from only one superclass. Dog extends Animal
Multilevel A class inherits from a class that already inherits from another class. BabyDog extends Dog extends Animal
Hierarchical Multiple classes inherit from a single superclass. Dog and Cat both extend Animal
Hybrid A combination of two or more types (achieved through classes and interfaces). SportsCar extends Car, and Car extends Vehicle (combines hierarchical and multilevel patterns)