File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Strange Java Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strange Java Code" Watch "Strange Java Code" New topic
Author

Strange Java Code

Igor Stojanovic
Ranch Hand

Joined: Feb 18, 2005
Posts: 58
The next one is strange. From the main(), we create a Foo instance, then we call getFoo() which returns a null and from "null" , we can access the value of fubar!



Can somebody explain this?
thx in advance

kind regards
Igor
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

The JVM doesn't need an object of class Foo to access the static variable fubar; just knowing the name of the class is enough. You can access a static variable "through" an object reference just as a convenience; the compiler generates the same code as it would if you just wrote "Foo.fubar" .

I believe I remember reading something regarding a possible change to the JLS that would require such a null access to give an error at runtime, but I don't think that change was ever made.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strange Java Code
 
Similar Threads
Regarding static
can we access null.[member]
unidirectional relationship
Overloaded varargs param doubt
Casting question