Implementing and extending, Interface and Abstract class respectively with same method name in java

dSanders :

I am trying to understand how default methods deal with diamond problem in various scenarios.
And, this is one of the scenario which I'm not able to understand.

Following is the description,
1. Interface with a default method method()
2. Abstract Class with a method method()
3. Concrete Class implementing the above interface and extending the abstract class.

interface Interface {
    default void method() {
        System.out.println("Interface method");
    }
}


abstract class AbstractClass {
    void method() {
            System.out.println("Abstract class method");
    }
}


// Concrete class definition first starts
public class ConcreteClass extends AbstractClass implements Interface {

    @Override
    public void method() {
        super.method();
    }

    public static void main(String[] args) {
        Interface test = new ConcreteClass();
        test.method();
    }
}
// Concrete class definition first ends

// Concrete class definition Second starts
public class ConcreteClass extends AbstractClass implements Interface {

    public static void main(String[] args) {
        Interface test = new ConcreteClass();
        test.method();
    }
}
// Concrete class definition Second ends

My queries,

1. Why does definition first always gives output as "Abstract class method" even when I use the Interface type for concrete class object?
2. Why definition second doesn't compile?
If compiler is using abstract class implementation in definition first, then it should be able to identify that it will always use Abstract class implementation in definition second.

This behavior is very confusing to me and any help is greatly appreciated. Otherwise, the more I delve deeper into this, the more confusing it gets.


Edit 1 :
Compilation error in second definition is "The inherited method AbstractClass.method() cannot hide the public abstract method in Interface"

Michael :

Default methods are just that: defaults. If there is an implementation, it will be used. If there isn't, the default will be used. There is no diamond problem here (there can be with multiple defaults, however).

1) Dynamic dispatch

2) The abstract class gives the method named method package-private access; the interface demands it be public.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327124&siteId=1