This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Agreed you can get static members from a class whose instances are all null, but are you really "using static members of a null variable," Stan James? The static references are to the class, and are available whether you have 0, 1 or 10000000 instances or null declarations of the class. In fact your String HELLO is loaded before the main method and before the "t" variable is declared.
Ofcourse you're not using "static members of a null variable". Static members are at the class level, not at the instance level. A static member does not belong to any specific instance, but to a class.
In my opinion, it should have been illegal in Java to call static methods on an instance (or on a reference variable, whether it is null or not). Calling static members on an instance is confusing and I don't know any reason why it would be necessary to have this as a feature in the language.
We often have questions in the forums from people who don't understand that static methods are not polymorphic. One of the reasons people get confused about this is because it's possible to call static methods on instances.
Always call static methods on the class, not on an instance:
[ April 18, 2007: Message edited by: Jesper Young ]
. . . and if Jesper Young had his wish and calling static methods on instances were prohibited (rather than simply raising a warning), we woul dhave a nice simple answer obvious to all who ask "can you call methods of a null reference?"
It would be NO.
And if by object's methods you mean methods which actually belong to that object, then it is still impossible to call them on a null reference.
Joined: Jan 29, 2003
"using static members of a null variable"
We'd have to agree on what that really means. The source code uses a variable t which is null, so I think I'm allowed to read it that way. Of course the compiler doesn't read it that way. It binds the method to the class and goes on its way. But if I tried to express every concept the way the compiler sees it, I'd have to be the compiler. Not a job I want.