Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors and inheritance

 
mythili sharan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi This qn is from Mindq.http://www.vivek.4mg.com/javacertification/jsexam.htm

I have a problem understanding Super sup = new Sub();
If any class has a superclass then the superclass constructor will be called while creating an object. so in this case a super object will be created even if sub constructor is called.
sup.index will be 5 and
sup.printVal will print super


but the answer is
c) The code compiles and "5, Sub" is printed to standard output.
Can anyone please explain where i am wrong in my understanding.


 
Tom Tolman
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables are resolved at compile time. Thus, the call to sup.index results in a fixed offset in memory from the base reference value. This points to the offset for Super- because that is what the reference value is defined to be. A reference to a Super.

However, methods are resolved dynamically. The call to sup.printVal() is resolved at run time. At this time, it sees that it ACTUALLY is of type sub, so dynamically binds this method and invokes the subclass version.

Does this answer your question?
 
Ken Weller
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tom Tolman:
However, methods are resolved dynamically. The call to sup.printVal() is resolved at run time. At this time, it sees that it ACTUALLY is of type sub, so dynamically binds this method and invokes the subclass version.


Keep in mind that this applies to instance methods only. Static methods are resolved based on the compile-time reference type.
 
Tom Tolman
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is an example of static binding vs dynamic binding:


output:

runner
walker
runner
talker
mumbler
mumbler
 
natarajan raman
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a real good one Tom....Very nice explanation.......Thanks a lot....
 
mythili sharan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much Tom.. the topic is now "claritin" clear. I shall never get such a question wrong again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic