This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange Java Code

 
Igor Stojanovic
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic