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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With