Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance and static initializers

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, here is another bit of code that is rather confusing (again from Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 12244-12246). Enthuware. Kindle Edition. )

What will the output be?
A. It will print In Sub and QBANK.
B. It will print QBANK.
C. Depends on the implementation of JVM.
D. It will not even compile.
E. None of the above.


Naturally I went for option A, but apparently it's B. No idea whatsoever why, as the explanation provided there makes absolutely no sense to me. Anyone who could explain it please?
thanks
 
Liutauras Vilda
Bartender
Pie
Posts: 2792
112
BSD VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:Anyone who could explain it please?
Answer:
Rephrased JLS wrote:Because the class Sub is never initialized. The reference to Sub.ID is a reference to a field actually declared in class Super and does not trigger initialization of the class Sub.
Check this JLS 12.4.1. part. It may be difficult to read, but couldn't find a better explanation than that.
 
Stephan van Hulst
Bartender
Pie
Posts: 6503
83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It was a mistake by the language designers to allow static fields to be accessed through object references and names of sub-classes. In your head, you should always read the code as if the access was actually done on the class where the field was declared.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic