Why multiple inheritance is not possible in java?

Java does not support multiple inheritance with classes, meaning a class cannot inherit from more than one class at the same time. This restriction helps avoid ambiguity and complexity that can arise when multiple parent classes contain methods or fields with the same name.

Key Points: • A Java class can extend only one class at a time. • Multiple inheritance can create ambiguity when parent classes have methods with identical signatures. • This problem is commonly known as the Diamond Problem. • Restricting multiple inheritance keeps the class hierarchy simple and easier to maintain. • Java achieves multiple inheritance of behavior through interfaces instead of classes.

Example: Suppose two parent classes contain a method named display(). If a child class inherits from both, Java would not know which display() method should be executed.

Code Example:

class Parent1 {

    void display() {
        System.out.println("Parent1");
    }
}

class Parent2 {

    void display() {
        System.out.println("Parent2");
    }
}

// Not Allowed in Java
class Child extends Parent1, Parent2 {

}

The above code would create ambiguity because Child inherits two versions of the display() method.

How Java Solves This:

Java allows a class to implement multiple interfaces:

interface Printer {
    void print();
}

interface Scanner {
    void scan();
}

class Machine implements Printer, Scanner {

    public void print() {
        System.out.println("Printing");
    }

    public void scan() {
        System.out.println("Scanning");
    }
}

This approach provides the benefits of multiple inheritance without the ambiguity associated with inheriting from multiple classes.

Interview Tip: A concise interview answer is:

"Java does not support multiple inheritance through classes to avoid ambiguity and the Diamond Problem, where multiple parent classes may contain methods with the same signature. Instead, Java supports multiple inheritance through interfaces, which provides flexibility without creating inheritance conflicts."