Page 1 of 1

Question about default method in interface

Posted: Thu Aug 11, 2016 8:35 am
by xc2016
There are two interfaces, and firstInterface contains a default method getTest(). secondInterface extends the firstInterface and re-declare the default method as abstract method getTest(). Class A implements these two interfaces and implements the abstract method getTest(); My question is if Class A implements a new version of the method that has same signature with default method in firstInterface, can I get access to the default method?. I tried

Code: Select all

firstInterface.super.getTest();
but it cannot compile.

Code: Select all

public interface firstInterface {
    public default int getTest(){
        return 5;
    }
}
public interface secondInterface extends firstInterface {
    public int getTest();
}
public class A implements firstInterface, secondInterface {
      @Override
    public int getTest() {
        
    System.out.println("implemented method is called");
    return 6;
    }
public class TEST3 {

    public static void main(String[] args) { 
        A sp = new A(5);
        sp.getTest();
        //firstInterface.super.getTest(); // compile error
        ((firstInterface)sb).getTest();
    }
  
}
the output is:
implemented method is called
implemented method is called

Re: Question about default method in interface

Posted: Thu Aug 11, 2016 12:35 pm
by admin
No, you cannot access the default method once the class that implements the interface redefines it.

Re: Question about default method in interface

Posted: Thu Aug 11, 2016 6:58 pm
by xc2016
I got it. Thank you!