更新时间:2023-12-03 16:27:34
因为它可能令人困惑!静态成员没有动态调度。
看看这个令人困惑的代码:(可能是语法错误;我的Java生锈了)
public abstract class Singer {
public static void sing(){
System.out.println(Singing);
}
}
公共类Soprano延伸歌手{
public static void sing(){
System.out.println(在范围内唱歌 C4-A5);
}
}
公共类MyDriver {
public static void main(String [] argv){
Singer mySoprano1 = new Soprano ();
女高音mySoprano2 =新女高音();
mySoprano1.sing();
mySoprano2.sing();
}
}
查看 MyDriver
令人困惑,因为似乎 sing
方法是多态的,所以输出应该是......
在C4-A5
$ p范围内$ p>
范围内演唱唱歌在C4-A5...因为
soprano1
和soprano2
都是实例Soprano
- 不是歌手
。但是,唉,输出实际上是:
唱歌
唱歌范围为C4-A5为什么?因为静态成员没有动态调度,所以声明的类型的
mySoprano1
确定哪个唱
方法被调用...并且声明的soprano1
的类型是Singer
,而不是女高音
。如需了解更多信息,请查看书中的拼图48我得到的都是静态的 Java Puzzlers 。
According to Java, static variable are accessible by Class name but they are also accessible by class object even though Java don't suggest it, and it gives the same answer.
I know there will be only one copy of the variable and its value will be same for all objects and other things. Why does Java suggest to use class name instead of class object?
Because it can be confusing! There is no dynamic dispatching on static members.
Take a look at this confusing code: (might be syntax errors; my Java is rusty)
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(); } }
Looking at
MyDriver
it's confusing because it seems like thesing
method is polymorphic so the output should be...Singing in the range of C4-A5 Singing in the range of C4-A5
... because both
soprano1
andsoprano2
are instances ofSoprano
- notSinger
.But alas, the output is actually:
Singing Singing in the range of C4-A5
Why? Because there is no dynamic dispatch on static members, so the declared type of
mySoprano1
determines whichsing
method is invoked... and the declared type ofsoprano1
isSinger
, notSoprano
.For more, check out Puzzle 48 "All I get is static" in the book Java Puzzlers.