What is zoo referring to in my code?

+5 Hemlata Mahaur · March 14, 2017
Zoo zoo = new Yoo();
Yoo yoo  = (Yoo) zoo;
In the first line zoo is referring to new Yoo(). When we write Yoo yoo = (Yoo) zoo, here I think it is referring to new Yoo(), as it is already referring to new Yoo() in the first line, and then we cast it to Yoo. I think I am probably wrong cuz why would it cast to something it is already referring? So my question is, is zoo referring to new Yoo() in the first line is same as yoo referring to zoo i.e; new Yoo() in the second line, before casting? Any help is appreciated!

/images/forum/upload/2017-03-14/cf29c1a31fabdbca032e5c30f209ea7c.png

Post a Reply

Replies

Oldest  Newest  Rating
0 Hemlata Mahaur · March 14, 2017
Zoo zoo = new Yoo();
Yoo yoo  = (Yoo) zoo;
This two lines  is in the class Yoo in the main method.
0 Hemlata Mahaur · March 14, 2017
Nicholas Eason I am waiting for your reply, cuz you always explain it really good :)
+1 Nicholas Eason · March 14, 2017
Okay. So, yes they are referring to the same object.

If you print both of the object's toString() methods (everything has one) you get the memory address of the object.



    Zoo zoo = new Yoo();
    Yoo yoo  = (Yoo) zoo;   
    System.out.println(zoo);
    System.out.println(yoo);


will print:

Yoo@4aa298b7
Yoo@4aa298b7


Those addresses are the same, so the variables are referencing the same thing.

Without casting, you'll get an error since zoo is a Zoo object; you can't create a Yoo object and assign it to a Zoo object.
0 Hemlata Mahaur · March 16, 2017
Thanks!
  • 1

Java / Android Development

126,540 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator