My doubt is the reference variable 'r' which was referencing rose object is now referencing flower object.
What happend to rose object now? Will it be destroyed?
I have the following code:
class Flower
{
public void smell() // I
{
System.out.println("All flowers give smell, if you can smell");
}
}
public class Rose extends Flower
{
public void smell() // II
{
System.out.println("Rose gives rosy smell");
}
public static void main(String args[])
{
Flower f = new Flower();
Rose r = new Rose();
f = r; // subclass to super class, it is valid
f.smell(); // II
}
}

It is Flower object which is eligible for garbage collection.
Rose object is still referred by both reference variable which is f and r.
Here you have assigned the rose to the f variable. This means that the instance of flower is now ready to be destroyed (garbaged collected).
f contains the rose, so f.smell() will result in Rose gives rosy smell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With