top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Multiple Inheritance in Java

Introduction

In this digital age, Java has become one of the most widely used programming languages, renowned for its portability and robustness. One of the fundamental concepts in Java is OOPs, of which there are four pillars, abstraction, encapsulation, polymorphism, and inheritance.

So what is inheritance exactly? It is a Java attribute that allows the user to create new classes by inheriting characteristics from existing ones. This tutorial will focus on multiple inheritance in Java and explore its various uses.

Overview 

Inheritance facilitates the creation of new classes that inherit attributes and behaviors from existing classes. It enables developers to establish connections between classes, fostering code reuse and promoting efficient development by managing time.

In lay terms, multiple inheritance in Java refers to the capability of a class to inherit properties from multiple interfaces, enabling code reuse, modularity, and versatility in class design. 

What is Multiple Inheritance?

Multiple inheritance in Java refers to the power of a class to inherit characteristics from more than one superclass at the same time. In the case of multiple inheritances, we can say that classes derive properties from multiple parent classes, thus forming class hierarchies. 

Why Use Inheritance in Java?

Inheritance is a cornerstone concept In Java programming, offering many advantages and allowing efficient, modular, and reusable code. Here we will delve into the compelling reasons why Java developers widely embrace inheritance, exploring the key benefits it brings to the table. 

  • Polymorphism refers to the ability of objects to take on multiple forms or behaviors.

  • You can create a hierarchy of related classes, each inheriting from a common superclass.

  • Inheritance also grants developers the power to override methods defined in the superclass within the subclass.

  • The mechanism known as method overriding lets you provide specialized implementations of methods in the derived classes.

  • By selectively overriding methods, you can customize and extend the behavior of the inherited functions tailoring it to suit the specific requirements of the subclass. 

Terms Used in Inheritance

This comprehensive guide will shed light on the essential and significant terms used in inheritance. By learning these terms, you'll gain clarity on the intricacies of inheritance and be able to wield its power effectively in your Java code. Let's explore the key terms associated with inheritance in Java.

  • Superclass/Base Class:

The superclass or base class is the existing class from which other classes inherit properties and behaviors. It serves as the foundation for the derived classes and defines the common characteristics inherited by its subclasses

  • Subclass/Derived Class:

A subclass or derived class is a new class created by inheriting properties and behaviors from a superclass. It specializes in the working of the superclass by adding new features or modifying existing ones.

  • Extends Keyword: 

The "extends" keyword is used in Java to establish an inheritance relationship between classes. It allows a subclass to inherit from a superclass. By specifying the superclass after the "extends" keyword, the subclass gains access to all the public and protected members of the superclass

  • Super Keyword: 

The "super" keyword in Java is used within a subclass to refer to its superclass. It can be used to access superclass members, invoke superclass constructors, and differentiate between superclass and subclass members with the same name.

  • Method Overriding: 

Method overriding is when subclasses implement methods already defined in superclasses. By overriding a method, the subclass can customize or extend the behavior inherited from the superclass.

  • super() Constructor Invocation: 

The "super()" constructor invocation is used in a subclass constructor to call the constructor of its superclass. It ensures that the superclass constructor is executed before the subclass constructor, allowing the initialization of inherited members.

  • final Keyword:

The "final" keyword is used in Java to indicate that a class, method, or variable cannot be extended, overridden, or modified, respectively. When applied to a class, it prevents inheritance, making it the final class in the hierarchy.

Java Inheritance Example

Here is an example of inheritance in Java:

// Parent class
class Vehicle {
    protected String brand;
    protected int year;
    public Vehicle(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }
    public void honk() {
        System.out.println("Honk honk!");
    }
}
// Child class inheriting from Vehicle
class Car extends Vehicle {
    private int numberOfDoors;
    public Car(String brand, int year, int numberOfDoors) {
        super(brand, year);
        this.numberOfDoors = numberOfDoors;
    }
    public void drive() {
        System.out.println("Driving the car");
    }
}
// Child class inheriting from Vehicle
class Motorcycle extends Vehicle {
    private boolean hasSidecar;
    public Motorcycle(String brand, int year, boolean hasSidecar) {
        super(brand, year);
        this.hasSidecar = hasSidecar;
    }
    public void wheelie() {
        System.out.println("Doing a wheelie!");
    }
}
// Main class to test the inheritance
public class Main {
    public static void main(String[] args) {
        Car car = new Car("Toyota", 2020, 4);
        car.honk();
        car.drive();
        Motorcycle motorcycle = new Motorcycle("Harley-Davidson", 2021, false);
        motorcycle.honk();
        motorcycle.wheelie();
    }
}

In this example, we have a parent class called Vehicle with two instance variables brand and year, and a method honk(). The child classes Car and Motorcycle inherit from the Vehicle class.

The Car class adds an additional instance variable numberOfDoors and a method drive(). The Motorcycle class adds an additional instance variable hasSidecar and a method wheelie().

In the Main class, we create objects of the Car and Motorcycle classes and call their respective methods to demonstrate inheritance.

Types of Inheritance in Java

Apart from multiple inheritance, Java has three kinds of inheritance. Let us explore them.

Single Inheritance Example 

Here is an example of single inheritance in Java:

// Parent class
class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
    public void eat() {
        System.out.println(name + " is eating.");
    }
}
// Child class inheriting from Animal
class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    public void bark() {
        System.out.println(name + " is barking.");
    }
}
// Main class to test the single inheritance
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy");
        dog.eat();
        dog.bark();
    }
}

In this example, we have a parent class called Animal with an instance variable name and a method eat(). The child class Dog inherits from the Animal class.

The Dog class adds a method bark(). It can access the name variable and the eat() method from the parent class.

In the Main class, we create an object of the Dog class and call its methods to demonstrate single inheritance.

Multilevel Inheritance Example

Here is an example of multilevel inheritance in Java:

// Grandparent class
class Animal {
    protected String species;
    public Animal(String species) {
        this.species = species;
    }
    public void eat() {
        System.out.println(species + " is eating.");
    }
}
// Parent class inheriting from Animal
class Dog extends Animal {
    public Dog() {
        super("Dog");
    }
    public void bark() {
        System.out.println("Dog is barking.");
    }
}
// Child class inheriting from Dog
class Labrador extends Dog {
    public Labrador() {
        System.out.println("Labrador is a type of Dog.");
    }
    public void playFetch() {
        System.out.println("Labrador is playing fetch.");
    }
}
// Main class to test the multilevel inheritance
public class Main {
    public static void main(String[] args) {
        Labrador labrador = new Labrador();
        labrador.eat();
        labrador.bark();
        labrador.playFetch();
    }
}

In this example, we have a grandparent class called Animal with an instance variable species and a method eat(). The parent class Dog inherits from the Animal class and adds a method bark(). The child class Labrador inherits from the Dog class and adds a method playFetch().

In the Main class, we create an object of the Labrador class and call its methods to demonstrate multilevel inheritance.

Hierarchical Inheritance Example

Here is an example of hierarchical inheritance in Java:

// Parent class
class Animal {
    protected String species;
    public Animal(String species) {
        this.species = species;
    }
    public void eat() {
        System.out.println(species + " is eating.");
    }
}
// Child class 1 inheriting from Animal
class Dog extends Animal {
    public Dog() {
        super("Dog");
    }
    public void bark() {
        System.out.println("Dog is barking.");
    }
}
// Child class 2 inheriting from Animal
class Cat extends Animal {
    public Cat() {
        super("Cat");
    }
    public void meow() {
        System.out.println("Cat is meowing.");
    }
}
// Main class to test the hierarchical inheritance
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.bark();
        Cat cat = new Cat();
        cat.eat();
        cat.meow();
    }
}

In this example, we have a parent class called Animal with an instance variable species and a method eat(). The child class Dog inherits from the Animal class and adds a method bark(). The child class Cat also inherits from the Animal class and adds a method meow().

In the Main class, we create objects of the Dog and Cat classes and call their respective methods to demonstrate hierarchical inheritance.

Example of Multiple Inheritance in Java (Alternative Method)

Java does not directly support multiple inheritance, where classes can inherit from multiple parent classes. However, you can achieve similar functionality using interfaces in Java.

Here's an example code that demonstrates a workaround for achieving multiple inheritance-like behavior using interfaces:

// First parent interface
interface Animal {
    void eat();
}
// Second parent interface
interface Mammal {
    void run();
}
// Child class implementing both interfaces
class Dog implements Animal, Mammal {
    @Override
    public void eat() {
        System.out.println("Dog is eating.");
    }
    @Override
    public void run() {
        System.out.println("Dog is running.");
    }
}
// Main class to test multiple inheritance-like behavior
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.run();
    }
}

In this example, we have two parent interfaces: Animal and Mammal. The Animal interface declares the eat() method, and the Mammal interface declares the run() method.

The Dog class implements the Animal and Mammal interfaces, effectively inheriting from both. It provides implementations for the eat() and run() methods.

In the Main class, we create an object of the Dog class and call its methods to demonstrate multiple inheritance-like behavior.

Why Multiple Inheritance is Not Supported in Java

Java intentionally omits multiple inheritance. Let's examine the rationale behind Java's decision to exclude multiple inheritance.

  • Diamond Problem: The diamond problem is a classic problem associated with multiple inheritance. It occurs when a class inherits from two or more superclasses that share a common superclass. Solving this issue becomes a complex task for the compiler, potentially leading to the code not working.

Java avoids the diamond problem and maintains code stability by excluding multiple inheritance.

  • Promoting Interface-based Inheritance: Java favors interface-based inheritance, which allows classes to implement multiple interfaces but inherits from only one superclass. Interfaces provide a way to define contracts, abstract methods, and shared behavior without introducing issues.

This design choice enhances code clarity, modularity, and extensibility, allowing developers to compose classes using interfaces and achieve similar benefits to multiple inheritance without the associated complexities.

Conclusion

As a language, Java does not support multiple inheritance to maintain simplicity. However, developers can utilize alternative techniques to achieve similar benefits while keeping the code’s clarity and maintainability.

Understanding these alternatives to multiple inheritance in Java helps developers to design maintainable code structures. By using such composition, interface-based inheritance, and the principle of composition over inheritance, developers can get code flexibility without any complexities associated with multiple inheritance.

FAQs

1. Why doesn't Java support multiple inheritance?

Java avoids multiple inheritance to maintain code simplicity and avoid any unnecessary bugs.

2. What are the alternatives to multiple inheritance in Java?

Alternatives to multiple inheritance in Java include composition, interface-based inheritance, and the principle of composition over inheritance.

3. Can multiple inheritance be achieved in Java using interfaces?

No, multiple inheritance cannot be achieved directly in Java using interfaces. However, classes can perform multiple interfaces, achieving similar results.

4. How can I overcome the limitations of multiple inheritance in Java?

The issues of multiple inheritance in Java can be solved by adding design patterns like the Adapter pattern or using composition and delegation to combine functions from multiple classes.

Leave a Reply

Your email address will not be published. Required fields are marked *