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.
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.
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.
Joined: Sep 02, 2004
Here is an example of static binding vs dynamic binding: