Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable in Java

Tags:

java

static

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?

like image 375
maddygoround Avatar asked Dec 27 '22 17:12

maddygoround


2 Answers

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.

like image 26
tskuzzy Avatar answered Jan 08 '23 02:01

tskuzzy


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.

like image 64
Richard JP Le Guen Avatar answered Jan 08 '23 02:01

Richard JP Le Guen