• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help me how the casting works in this program  RSS feed

 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Robert D. Smith
Ranch Hand
Posts: 221
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm sorry, I tried following your code, but I couldn't keep track of how many { vs } you had. Code Tags (see the 'Code' button on the same line as the bold, underline, etc) and proper indentation will help immensely.

And I couldn't see where you were trying to cast a value -- but that could just be me not understanding your question.

Regards,
Robert
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so you posted some code. Please explain what exactly your question is with regard to casting.
 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

explain me this line
Animal a2=new Ret1();
Ret1 k=(Ret1)a2;
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bairava surya wrote:
explain me this line
Animal a2=new Ret1();


With this line, you are instantiating a Ret1 object, and is assigning an Animal reference to refer to it. This works because a Ret1 IS-A Animal type.

bairava surya wrote:
Ret1 k=(Ret1)a2;


With this line, you are assigning the object (referred to by the a2 reference) to a Ret1 reference. This is a legal maneuver because the a2 reference is referring to a Ret1 instance... but the compiler doesn't know that, so it will complain.

You however, know better -- and cast it, which is basically telling the compiler that it is are correct, and to allow the assignment... In other words, that cast is telling the compiler to treat the instance referred to by the a2 reference, as a Ret1 type.

Henry
 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot !
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!