Kubernate

Thursday, November 13, 2025

Java - Multiple Inheritance (Not Support in Classes) But through interface

 Java does not support multiple inheritance with classes, but it does support multiple inheritance through interfaces. Here's a breakdown:


❌ Multiple Inheritance with Classes

Java avoids multiple inheritance with classes to prevent ambiguity and complexity—especially the Diamond Problem, where the compiler can't decide which superclass method to inherit if multiple paths exist.

class A {
    void show() {
        System.out.println("A");
    }
}

class B {
    void show() {
        System.out.println("B");
    }
}

// ❌ This is illegal in Java
class C extends A, B {  // Compilation error
    // ...
}

✅ Multiple Inheritance with Interfaces

Java allows a class to implement multiple interfaces, which is a form of multiple inheritance.

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() {
        System.out.println("Duck flies");
    }

    public void swim() {
        System.out.println("Duck swims");
    }
}

This is safe because interfaces only declare methods (no state), and Java resolves conflicts clearly when default methods are involved.


⚠️ What About Default Methods?

Since Java 8, interfaces can have default methods with implementations. If two interfaces have the same default method, the implementing class must override it to resolve the conflict.

interface A {
    default void greet() {
        System.out.println("Hello from A");
    }
}

interface B {
    default void greet() {
        System.out.println("Hello from B");
    }
}

class C implements A, B {
    public void greet() {
        System.out.println("Custom greeting from C");
    }
}


No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. 🔄 Spring Boot Applica...

Kubernate