因为可能会造成混淆!静态成员上没有动态调度。
看一下这个令人困惑的代码:(可能是语法错误;我的Java生锈了)
public abstract class Singer { public static void sing() { System.out.println("Singing"); }}public class Soprano extends Singer { public static void sing() { System.out.println("Singing in the range of C4-A5"); }}public class MyDriver { public static void main(String[] argv) { Singer mySoprano1 = new Soprano(); Soprano mySoprano2 = new Soprano(); mySoprano1.sing(); mySoprano2.sing(); }}看起来
MyDriver很混乱,因为
sing方法似乎是多态的,所以输出应该是…
Singing in the range of C4-A5Singing in the range of C4-A5
…因为
soprano1和
soprano2都是
Soprano-不是的实例
Singer。
但可惜的是,输出实际上是:
SingingSinging in the range of C4-A5
为什么?由于静态成员上没有动态分配,因此, 声明的
类型
mySoprano1确定
sing调用哪个方法…,而声明的类型
soprano1为
Singer,不是
Soprano。
有关更多信息,请参阅Java Puzzlers一书中的Puzzle
48“我所得到的都是静态的” 。



