0

I have a Query Suppose I have a 2 interface f1 and f2 and f2 interface extends f1 interface. both interface have default method m1 with some implementation. now we have a class c1 which implements f2 interface and we override m1() method. now i can access f2 default method. f2.super.m1(). how can i access f1 interface default method. Please clarify me is it possible or not?

interface f1{
    public default void m1() {
        System.out.println("f1");
    };
}
interface f2 extends f1{
    public default void  m1(){
        System.out.println("f2");
    };
}
public class techgig implements f2 {
    public static void main(String[] args) {
        techgig a = new techgig();
    a.m1();
    }
    @Override
    public void m1() {
        // TODO Auto-generated method stub
        f2.super.m1();
    }
}

It will print f2 but i want to print f1

1 Answers1

0

You can see the followong from java docs.

Extending Interfaces That Contain Default Methods:

When you extend an interface that contains a default method, you can do the following:

  • Not mention the default method at all, which lets your extended interface inherit the default method.
  • Redeclare the default method, which makes it abstract.
  • Redefine the default method, which overrides it.

from the documentation we can see when we extends an interface that has a default method. If we redefine the default method, it will override the default method. In your case interface f1 default method is overridden by implementation in f2 interface.

If you want to get the output of default method in interface f1 don't redefine the default method in interface f2.

If you change your interface f2 as below you will get the output "f1".

interface f2 extends f1 {
    
}

Reference: Default Methods

deadshot
  • 8,881
  • 4
  • 20
  • 39