• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Strange Java Code

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic