File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Reference casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference casting" Watch "Reference casting" New topic

Reference casting

vinayak manda
Ranch Hand

Joined: Jul 27, 2004
Posts: 31
class Example { }
class Example1 extends Example{
public static void main(String args[]){
Example1 e1[] = { new Example1()};
Example e[] = { new Example()};
Object o =e1;
e1=(Example1[])o; //compiles and runs well

Example e2 = new Example();
Example1 e3=(Example1)e2; //why doesn't this run well and throws a class cast exception
Please explain
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059

e1 is an object of type Example1. You declared it as such in line 3.
e2 is not an object of type Example1. It is an object of type Example. You cannot cast it to any type other than what it is or a subclass of that type. Thus, because e1 is an object of type Example1 and also is an object of type Example, it can be cast to either of those.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jack Kay
Ranch Hand

Joined: Aug 01, 2004
Posts: 62
Let's take this example:


Let's say you create a new Car:
Car myCar = new Car();

You can't go like this:
Pinto myPinto = (Pinto)myCar;

Because the Car is NOT a Pinto. But you can go like this:
Pinto myPinto = new Pinto();
Car myCar = (Car)myPinto;

The Pinto loses its functionality as being a Pinto, when put into the myCar variable, it IS still a pinto, but it doesn't KNOW it's a pinto. So you can't go like this:


You have to reconvert it to being a Pinto:

myPinto = (Pinto)myCar;

Hope that helps you!
I agree. Here's the link:
subject: Reference casting
It's not a secret anymore!