如图http://docs.oracle.com/javase/tutorial/java/IandI/override.html , Java 允许
- 通过实例方法覆盖实例方法并
- 通过静态方法隐藏静态方法
我的问题是为什么 Java 不允许通过实例方法隐藏静态父类(super class)方法。这可以这样做:
class Base {
static void foo () {}
}
class Derived extends Base {
void foo () {}
void access () {
foo ();
Base.foo ();
}
}
我没有看到上述方法有任何特别的问题 - 它只是像(允许的)静态隐藏一样“困惑/复杂”。
最佳答案
我怀疑这是为了避免与处理基类混淆。事实上,我认为设计师没有看到它应该表现的明显方式。
class Base {
static void foo () {}
}
class Derived extends Base {
void foo () {} // say this compiled
}
Base b = new Derived()
b.foo(); // should the static or the virtual method be called?
b.foo() 应该调用 Base.foo() 还是应该调用 Derived.foo()?
关于java - 为什么 Java 不允许通过实例方法隐藏静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14602220/