有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调用superinterface的默认方法是否可行?

假设我有两个类,AB

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

在将B实例化为b之后,我可以调用B的方法,如b.method()。我还可以使用super.method()调用A的方法。但是如果A是一个接口,该怎么办呢

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

有没有办法让B的方法调用A的方法


共 (1) 个答案

  1. # 1 楼答案

    是的,你可以。使用

    A.super.method();
    

    {a1}国家

    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.