Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class Cast related query

 
Debapriya Mukherjee
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was trying this below code:



I really want to know what actually happens in Memory for these below two lines:
A a1 = new B();
B b1 = (B)a1;

Also I want to know the use of Upcasting,just some example from Practical life where we really need to use it.

I am not able to visualize this .
 
Jim Pouwels
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. You create a new reference variable and assign a new B object to it. You can only invoke methods implemented by A on the B object.
2. You create a new reference variable, which refers to exactly the same object as the first variable

Concluding: You've just created 1 object, and two variables referring to that object!

There are many cases in which you'd want to use upcasting. F.e. when you want to do some generic things for all subclasses of a particular class.

F.e.:



Are you sure you're talking about upcasting? Since upcasting is always implicit. Am I wrong here?
 
Debapriya Mukherjee
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I created an Object of Type B.But when I assigned it to superclass Object reference(which is a1) the upcating happened automatically.
although it was a B type object now it will behave like a1.It lost its specific Properties other than the generic.
Then I performed the downcast to obtain the lost specific properties of the Object of type B.


I hope my understanding is correct now?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic