问题
Say I have two classes, A and B:
class A
{
void method()
{
System.out.println("a.method");
}
}
class B extends A
{
@Override
void method()
{
System.out.println("b.method");
}
}
After instantiating B as b, I can call B's method like b.method(). I can also make B's method call A's method with super.method(). But what if A is an interface:
interface A
{
default void method()
{
System.out.println("a.method");
}
}
class B implements A
{
@Override
void method()
{
System.out.println("b.method");
}
}
Is there any way I can make B's method call A's method?
回答1:
Yes, you can. Use
A.super.method();
The JLS states
If the form is
TypeName . super . [TypeArguments] Identifier, then:It is a compile-time error if
TypeNamedenotes neither a class nor an interface.If
TypeNamedenote 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
Tbe the type declaration immediately enclosing the method invocation. It is a compile-time error ifTis the class Object.Otherwise,
TypeNamedenotes the interface to be searched,I.
来源:https://stackoverflow.com/questions/22913784/is-calling-a-superinterfaces-default-method-possible