aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I don't understand the result of this question, could somebody please explain me? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "I don Watch "I don New topic
Author

I don't understand the result of this question, could somebody please explain me?

sura watthana
Ranch Hand

Joined: Sep 13, 2004
Posts: 77
I have a question regarding polymorphism. Here is the question

public class Polymorphism {
public static void main(String[] args) {
D ref1 = new F();
E ref2 = (E) ref1;
System.out.println(ref2.fn());
}
}

class D { int fn() { return 0; } }
class E extends D { int fn() { return 1; } }
class F extends E { int fn() { return 2; } }


so what is gonna be the answer and why, thanks for your help.

Sura
Tom Tolman
Ranch Hand

Joined: Sep 02, 2004
Posts: 83
The output is going to be 2. The reason is that polymorphism means - dynamically figure out which method to call based on the actual instance type. So we start out with a new F. This is an F. It is marked as an F internally with a special marker.

Now we assign this to a D reference. This is fine- object references can point to the subclass or any base class. However, the object itself is an F. Later we could say ref1 = new D(); and that would be valid as well.

Now we tell it- we have another reference, this one is called ref2, and it points to something of type E. We assign it to the original object F. This is fine as well- the F is a subclass of E.

Now finally, we ask to call the function on ref2. It is pointing to the object of type F. It dynamically resolves this, and says- what is the function for F? The one that returns 2.

It returns 2.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I don't understand the result of this question, could somebody please explain me?
 
Similar Threads
access modifier
Queries
Polimorphism x Casting
object references
Polymorphism