Static variable in Java

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 the sing 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 and soprano2 are instances of Soprano - not Singer .

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 which sing method is invoked... and the declared type of soprano1 is Singer , not Soprano .

For more, check out Puzzle 48 "All I get is static" in the book Java Puzzlers.


It is more self-documenting if you write MyClass.staticVariable than myObject.staticVariable . It tells the person looking at the code that staticVariable is a property of MyClass , as opposed to myObject which is a particular instance of the class.


One point I can think is if you use Class Reference instead of Object, JVM does not need to create a new Object at all to access that static variable. This is a good programming practice for performance.

链接地址: http://www.djcxy.com/p/78804.html

上一篇: Java中运行静态/实例初始化程序块的顺序是什么?

下一篇: Java中的静态变量