gpt4 book ai didi

java - 是否可以调用 super 接口(interface)的默认方法?

转载 作者:行者123 更新时间:2023-12-02 05:57:54 26 4
gpt4 key购买 nike

假设我有两个类(class),AB :

class A
{
void method()
{
System.out.println("a.method");
}
}
class B extends A
{
@Override
void method()
{
System.out.println("b.method");
}
}

实例化后Bb ,我可以调用B的方法如 b.method() 。我还可以做B的方法调用 A的方法 super.method() 。但如果A呢?是一个接口(interface):

interface A
{
default void method()
{
System.out.println("a.method");
}
}
class B implements A
{
@Override
void method()
{
System.out.println("b.method");
}
}

有什么办法可以让B的方法调用 A的方法?

最佳答案

是的,可以。使用

A.super.method();

JLS

If the form is TypeName . super . [TypeArguments] Identifier, then:

It is a compile-time error if TypeName denotes neither a class nor an interface.

If TypeName denote a class, C, then the class to search is the superclass of C.

It is a compile-time error if C is not a lexically enclosing type declaration of the current class, or if C is the class Object.

Let T be the type declaration immediately enclosing the method invocation. It is a compile-time error if T is the class Object.

Otherwise, TypeName denotes the interface to be searched, I.

关于java - 是否可以调用 super 接口(interface)的默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22913784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com