Default Methods with Multiple Inheritance

A class in java can implement multiple Interfaces. the Interface can have the same method definition. Abstract methods don't have an implemented body, so at the time of execution, the compiler will call the implementing class overridden implementation.

package org.wesome.dsalgo.java8;

interface Fruit {
    void likedFruit(String fruitName);
}

interface Vegetable {
    void likedFruit(String fruitName);
}

class Eat implements Fruit, Vegetable {
    @Override
    public void likedFruit(String fruitName) {
        System.out.println("Eat class overriding likedFruit method, i love = " + fruitName);
    }

    public static void main(String[] args) {
        Eat eat = new Eat();
        eat.likedFruit("Apple");
    }
}

Since Java 8 release, Interfaces can also have default method implementations, so at the time of execution, this will create confusion for compiling to execute which Interface default method implementation.

to resolve this diamond problem, the super keyword is used along with the Interface name.

package org.wesome.dsalgo.java8;

interface Fruit {
    default void likedFruit(String fruitName) {
        System.out.println("Fruit.likedFruit, i love = " + fruitName);
    }
}

interface Vegetable {
    default void likedFruit(String fruitName) {
        System.out.println("Vegetable.likedFruit, i love = " + fruitName);
    }
}

class Eat implements Fruit, Vegetable {
    @Override
    public void likedFruit(String fruitName) {
        Fruit.super.likedFruit(fruitName);
        Vegetable.super.likedFruit(fruitName);
    }

    public static void main(String[] args) {
        Eat eat = new Eat();
        eat.likedFruit("Apple");
    }
}

 

follow us on