Static and non static methods with the same name in parent class and implementing interface(父类和实现接口中同名的静态和非静态方法)
问题描述
我不是在问接口和抽象类之间的区别。
这是单打独斗的成功,对吗?
interface Inter {
public void fun();
}
abstract class Am {
public static void fun() {
System.out.println("Abc");
}
}
public class Ov extends Am implements Inter {
public static void main(String[] args) {
Am.fun();
}
}
为什么会发生冲突?
推荐答案
Astatic
和非static
方法在相同的class
中不能有相同的签名。这是因为您可以使用引用访问static
和非static
方法,而编译器将无法决定是要调用static
方法还是非static
方法。
以下面的代码为例:
Ov ov = new Ov();
ov.fun(); //compiler doesn't know whether to call the static or the non static fun method.
Java之所以允许使用引用调用static
方法,是为了让开发人员可以无缝地将static
方法更改为非static
方法。
这篇关于父类和实现接口中同名的静态和非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!