• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

potential gotcha in Inheritance you need to know

 
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[/B]
Guess what is the result ?
Well....I am hoping that most of you got it wrong
Just kidding...
The answer is
Square Area
0
I was quite surprised at the first go.... but I think I understand it vaguely...
Anyone willing to explain it clearly is most welcome as my concepts are stilla bit shaky on this particular problem
Thanks in advance
Sri
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has to do with forward referencing and not necessarly inheritance.
Basically, when a new Square object is created, the superclass object (Shape) is created and initialized. When the initialization of the Shape object occurs, the instance member "area" is initialized with the value returned by the getArea method. Since getArea is overridden in Square, it is invoked and returns the current value of the area instance member of the Square class which still has a default value of 0 since the Square class has not been initialized yet. That's why the area instance variable of the Shape class has the value 0.
Please check out JLS 8.3.2.3 Restrictions on the use of Fields during Initialization which explains a similar example.
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot, that was a very good explanation
sri
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is one of the reasons to avoid calling overridable methods from constructors. Doing so just invites disaster later when somebody wants to write a subclass.
See Joshua Bloch's book "Effective Java Programming Language Guide", item 15.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic