这里提出了一些问题,为什么你不能在接口中定义静态方法,但它们都没有解决基本的不一致性:为什么你可以在接口中定义静态字段和静态内部类型,而不是静态方法?
静态内部类型可能不是一个公平的比较,因为这只是产生一个新类的语法糖,但为什么是字段而不是方法?
接口中的静态方法的一个参数是它破坏了JVM使用的虚拟表解析策略,但是不应该同样适用于静态字段,即编译器可以内联它吗?
一致性是我想要的,Java应该支持接口中没有任何形式的静态,或者它应该是一致的并允许它们.
我知道在Java中,静态方法就像实例方法一样继承,不同之处在于,当重新声明它们时,父实现被隐藏而不是被覆盖.好吧,这很有道理.但是,Java教程指出了这一点
接口中的静态方法永远不会被继承.
为什么?常规和接口静态方法有什么区别?
当我说静态方法可以继承时,让我澄清一下我的意思:
class Animal {
public static void identify() {
System.out.println("This is an animal");
}
}
class Cat extends Animal {}
public static void main(String[] args) {
Animal.identify();
Cat.identify(); // This compiles, even though it is not redefined in Cat.
}
Run Code Online (Sandbox Code Playgroud)
然而,
interface Animal {
public static void identify() {
System.out.println("This is an animal");
}
}
class Cat implements Animal {}
public static void main(String[] args) {
Animal.identify();
Cat.identify(); // This does not compile, because interface …Run Code Online (Sandbox Code Playgroud) 为什么我不能使用实例变量访问接口的静态方法.
public class TestClass {
public static void main(String[] args) {
AWD a = new Car();
a.isRearWheelDrive(); //doesn't compile
}
}
interface AWD {
static boolean isRearWheelDrive() {
return false;
}
}
class Car implements AWD {
}
Run Code Online (Sandbox Code Playgroud)