根据Java,静态变量可以通过类名访问,但它们也可以通过类对象访问,即使Java没有建议它,它给出了相同的答案.
我知道变量只有一个副本,它的值对于所有对象和其他东西都是相同的.为什么Java建议使用类名而不是类对象?
因为它可能令人困惑!静态成员没有动态调度.
看看这个令人困惑的代码:(可能是语法错误;我的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();
}
}
Run Code Online (Sandbox Code Playgroud)
看着MyDriver它令人困惑,因为看起来这个sing方法是多态的,所以输出应该是......
Singing in the range of C4-A5
Singing in the range of C4-A5
Run Code Online (Sandbox Code Playgroud)
......因为这两个soprano1和soprano2的实例Soprano-不是Singer.
但是,唉,输出实际上是:
Singing
Singing in the range of C4-A5
Run Code Online (Sandbox Code Playgroud)
为什么?因为静态成员上没有动态调度,所以声明的类型mySoprano1确定sing调用哪个方法...而声明的类型soprano1是Singer,而不是Soprano.
有关更多信息,请参阅Java Puzzlers一书中的Puzzle 48"All I get is static" .