为什么在接口中,从默认接口方法调用静态接口方法我不能使用this.staticInterfaceMethod()
,而在常规类中,从实例方法调用静态类方法使用this.staticClassMethod()
是完全有效的(尽管它是不好的风格)?
同时,在默认的接口方法中使用this
是完全有效的 - 我可以合法地执行以下操作:
interface I {
int MY_CONST = 7;
static void st_f() {}
default void f1() {}
default void f_demo() {
this.f1(); // fine!
int locvar = this.MY_CONST; // also fine!
this.st_f(); // c.ERR: static method of interface I can only be accessed as I.st_f
}
}
"静态方法只能在包含接口类时调用。
静态方法不是由实现接口的类从接口继承的 (§8.4.8)。this
关键字引用当前对象,因此尝试调用this.staticInterfaceMethod()
将意味着以某种方式存在继承了静态接口方法的对象。这不可能发生;接口不能由自身实例化,并且接口的任何实现都不会继承静态方法。因此,this.staticInterfaceMethod()
不存在,因此您需要在接口本身上调用该方法。
关于为什么不继承静态方法的简化解释是以下方案:
public interface InterfaceA {
public static void staticInterfaceMethod() {
...
}
}
public interface InterfaceB {
public static void staticInterfaceMethod() {
...
}
}
public class ClassAB implements InterfaceA, InterfaceB {
...
}
ClassAB
继承什么静态方法?这两个静态方法具有相同的签名,因此在调用时无法识别;两者都不会隐藏对方。
同时,在默认的接口方法中使用它也是完全有效的。
允许使用this
关键字引用默认方法、变量等,因为从接口继承的每个可以存在的 Object 都将继承这些属性。