Can we perform multiple inheritance in Java?

Java MCQ: Can we perform multiple inheritance in Java?

A. Yes
B. No

Answer:

B. No

Explanation:

Java does not support multiple inheritance with classes, meaning a class cannot extend more than one class at a time. This decision was made to avoid the complexity and potential ambiguity that can arise from multiple inheritance, such as the “diamond problem,” where a class could inherit the same method from multiple parent classes, leading to ambiguity about which method to use.

Instead, Java allows multiple inheritance through interfaces. A class can implement multiple interfaces, allowing it to inherit the method signatures from several sources. This approach provides the benefits of multiple inheritance without the associated risks and complexities. For example:


interface Drivable {
    void drive();
}

interface Flyable {
    void fly();
}

class FlyingCar implements Drivable, Flyable {
    public void drive() {
        System.out.println("Driving the car");
    }

    public void fly() {
        System.out.println("Flying the car");
    }
}

In this example, the FlyingCar class implements two interfaces, Drivable and Flyable, and provides implementations for both drive() and fly() methods. This way, Java allows a form of multiple inheritance while keeping the language simple and avoiding potential conflicts.

Understanding this limitation and the use of interfaces is crucial for designing robust Java applications. By using interfaces wisely, developers can achieve the benefits of multiple inheritance without encountering the pitfalls that typically come with it in other languages.

Reference links:

https://www.javaguides.net/p/java-inheritance-tutorial.html

Leave a Comment

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

Scroll to Top