为什么在接口中,从默认接口方法调用静态接口方法我不能使用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
}
}
Run Code Online (Sandbox Code Playgroud)
“静态方法只能在包含接口类时调用。”
\n\n实现接口的类 ( \xc2\xa78.4.8 ) 不会从接口继承静态方法。该this关键字引用当前对象,因此尝试调用this.staticInterfaceMethod()将意味着以某种方式存在继承了静态接口方法的对象。这是不可能发生的;接口不能自行实例化,并且接口的任何实现都不会继承静态方法。因此,this.staticInterfaceMethod()不存在,因此您需要调用接口本身的方法。
关于为什么不继承静态方法的简单解释是以下场景:
\n\npublic interface InterfaceA {\n public static void staticInterfaceMethod() {\n ...\n }\n}\n\npublic interface InterfaceB {\n public static void staticInterfaceMethod() {\n ...\n }\n}\n\npublic class ClassAB implements InterfaceA, InterfaceB {\n ...\n}\nRun Code Online (Sandbox Code Playgroud)\n\n什么静态方法会ClassAB继承?这两个静态方法具有相同的签名,因此在调用时无法识别;双方都不会隐藏对方。
\n\n\n同时,在接口的默认方法中使用它是完全有效的。
\n
允许使用this关键字引用默认方法、变量等,因为从接口继承的每个可能存在的对象都将继承这些属性。
| 归档时间: |
|
| 查看次数: |
1266 次 |
| 最近记录: |