my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors and inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors and inheritance" Watch "Constructors and inheritance" New topic
Author

Constructors and inheritance

mythili sharan
Greenhorn

Joined: Sep 23, 2004
Posts: 4
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

Joined: Sep 02, 2004
Posts: 83
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

Joined: Aug 20, 2004
Posts: 24
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.


SCJP 1.4
Tom Tolman
Ranch Hand

Joined: Sep 02, 2004
Posts: 83
Here is an example of static binding vs dynamic binding:


output:

runner
walker
runner
talker
mumbler
mumbler
natarajan raman
Greenhorn

Joined: Apr 10, 2004
Posts: 26
That's a real good one Tom....Very nice explanation.......Thanks a lot....


nata.r<br />**********************************<br />To win is not always success<br />And to lose is not always failure.<br />**********************************
mythili sharan
Greenhorn

Joined: Sep 23, 2004
Posts: 4
Thanks so much Tom.. the topic is now "claritin" clear. I shall never get such a question wrong again.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Constructors and inheritance