wood burning stoves 2.0*
The moose likes Java in General and the fly likes Class Cast related query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Class Cast related query" Watch "Class Cast related query" New topic
Author

Class Cast related query

Debapriya Mukherjee
Greenhorn

Joined: Mar 07, 2012
Posts: 4
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

Joined: Feb 22, 2012
Posts: 61
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

Joined: Mar 07, 2012
Posts: 4
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Class Cast related query