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)
Looking at
MyDriverit’s confusing because it seems like thesingmethod is polymorphic so the output should be…… because both
soprano1andsoprano2are instances ofSoprano– notSinger.But alas, the output is actually:
Why? Because there is no dynamic dispatch on static members, so the declared type of
mySoprano1determines whichsingmethod is invoked… and the declared type ofsoprano1isSinger, notSoprano.For more, check out Puzzle 48 “All I get is static” in the book Java Puzzlers.