简体   繁体   English

我需要明确 java 接口中默认方法的具体条件

[英]I need clarity on specific condition on default method in interface in java

I have a Query Suppose I have a 2 interface f1 and f2 and f2 interface extends f1 interface.我有一个查询假设我有一个 2 接口 f1 和 f2 和 f2 接口扩展了 f1 接口。 both interface have default method m1 with some implementation.两个接口都有默认方法 m1 和一些实现。 now we have a class c1 which implements f2 interface and we override m1() method.现在我们有一个实现 f2 接口的 class c1 并且我们覆盖了 m1() 方法。 now i can access f2 default method.现在我可以访问 f2 默认方法。 f2.super.m1(). f2.super.m1()。 how can i access f1 interface default method.我如何访问 f1 界面默认方法。 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它会打印 f2 但我想打印 f1

You can see the followong from java docs.您可以从 java 文档中看到以下内容。

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.在您的情况下,接口f1默认方法被f2接口中的实现覆盖。

If you want to get the output of default method in interface f1 don't redefine the default method in interface f2 .如果要获取接口f1中默认方法的 output ,请不要重新定义接口f2中的默认方法。

If you change your interface f2 as below you will get the output "f1".如果你改变你的接口f2如下你会得到 output "f1"。

interface f2 extends f1 {
    
}

Reference: Default Methods参考: 默认方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM