Question about default method in interface

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
xc2016
Posts: 4
Joined: Wed Aug 10, 2016 11:05 am
Contact:

Question about default method in interface

Post 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

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Question about default method in interface

Post by admin »

No, you cannot access the default method once the class that implements the interface redefines it.
If you like our products and services, please help us by posting your review here.

xc2016
Posts: 4
Joined: Wed Aug 10, 2016 11:05 am
Contact:

Re: Question about default method in interface

Post by xc2016 »

I got it. Thank you!

Post Reply

Who is online

Users browsing this forum: No registered users and 46 guests