Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Variable in Java?

Tags:

java

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

 }
}
like image 906
Abhinav Avatar asked Jan 21 '26 18:01

Abhinav


2 Answers

enter image description here

It is Flower object which is eligible for garbage collection. Rose object is still referred by both reference variable which is f and r.

like image 89
AmitG Avatar answered Jan 23 '26 06:01

AmitG


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.

like image 27
Colin Hebert Avatar answered Jan 23 '26 07:01

Colin Hebert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!