Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes Exception whith Cast ...it's strange Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception whith Cast ...it Watch "Exception whith Cast ...it New topic
Author

Exception whith Cast ...it's strange

Engin Okucu
Ranch Hand

Joined: Feb 09, 2002
Posts: 174
Hi everybody...
I have a problem when i cast a object of a base class ... as follow :
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
public static void main(String args[]) {
A x = new A();
B y = new B();
C z = new C();
x = y; //line 1 it's OK
y = (B) x; //line 2 it's OK
z = (C) x; //line 3 but here,it doesn't work
}
}
My question is : I want to know why when i cast at line 2 i don't have a ClassCastException but when i do it for the line 3 i have one. Nevertheless it's done the same way so for line 3 than at line 2 ? isn't it?
Can you explain me it please.....
Thanks a lot !
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Okucu
Lets look at it line by line:
A x = new A();
B y = new B();
The variable x holds a reference to an A object, the variable y holds a reference to a B object.
x = y; //line 1 it's OK
Now the variable x holds a refernce to a B object, this is ok because a B object 'is a' A object.
y = (B) x; //line 2 it's OK
You are casting the reference that x holds to a B object (y was declared to hold a B object reference). This is ok because in the line before this on ewe changed the x variable to point to a B object.
z = (C) x;
Here you are casting the reference in x to a C object. But x doesn't hold a C object it is a B object (or an A object because a B object 'is a' A object).
hope that clears it up for you


Dave
Engin Okucu
Ranch Hand

Joined: Feb 09, 2002
Posts: 174
Dave , i thanks a lot, now it clears me up more.
I did understand it.
If i had created a refence to z variable than i would be able to compile whithout problem as follow :
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
public static void main(String args[]) {
A x = new A();
B y = new B();
C z = new C();
x = y;
y = (B) x;
// x=z; ------------ this line
z = (C) x;

}
}
By adding my commentary line (referenced by 'this line' into the program) i can compile. I had completely forget than x was a object of typa A. And to cast it, a reference of the variable x must be created to subclass before casting so that it may work !
Thanks.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception whith Cast ...it's strange
 
Similar Threads
Reference Casting
RuntimeException
Three Questions from Khalid's mock exam
Casting
Cast Question