permaculture playing cards*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference casting" Watch "Reference casting" New topic
Author

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
Sheriff

Joined: Jul 22, 2000
Posts: 9043
    
  10

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.


JavaBeginnersFaq
"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:

-Vehicle
--Car
---Pinto

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:

myCar.bePinto();

You have to reconvert it to being a Pinto:

myPinto = (Pinto)myCar;


Hope that helps you!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference casting
 
Similar Threads
Garbage Collection question
packages
why they use hashCode() method in equals() method
problem with wait()- notify()
IllegalMonitorStateException from notify()