• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference casting

 
vinayak manda
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Jack Kay
Ranch Hand
Posts: 62
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic