Forums Register Login

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

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
Let nothing stop you! Not even this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 598 times.
Similar Threads
access modifier
Queries
Polimorphism x Casting
object references
Polymorphism
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 01:55:06.