| Author |
casting question
|
henry wu
Greenhorn
Joined: Dec 01, 2000
Posts: 23
|
|
with this code: class Alpha {} class Beta extends Alpha {} class Chi extends Alpha {} public class CastTest { public static void main(String [] args) { Alpha a = new Alpha(); Beta b = new Beta(); Chi c = new Chi(); a=b; //b=c; //need explicit cast b = (Beta)a; //should be OK to downcast //b = (Beta)c; //can't cast to sibling classes //c = (Alpha)c; //same as saying c=a } } This is what I think: 1)[ a=b ] will work because b is a subclass of a so its implicitly cast. 2)[ b=c ] needs explicit cast since its a downcast (compile error) 3) [ b = (Beta)a] should be ok since it is explicitly downcasted (no runtime error for me) 4) [ b = (Beta)c ] can't cast to sibling classes (compile error) 5) [ c = (Alpha)c] same as 2.. can't make c=a since that is a downcast So it looks like 1 and 3 will compile and run. And 2,4,5 are all compile time errors. Is this correct? Henry
|
 |
chi Lin
Ranch Hand
Joined: Aug 24, 2001
Posts: 348
|
|
Henry, for 2, even with explict cast, you will stay have a compiler error. Everything else seems correct.
Originally posted by henry wu: with this code: class Alpha {} class Beta extends Alpha {} class Chi extends Alpha {} public class CastTest { public static void main(String [] args) { Alpha a = new Alpha(); Beta b = new Beta(); Chi c = new Chi(); a=b; //b=c; //need explicit cast b = (Beta)a; //should be OK to downcast //b = (Beta)c; //can't cast to sibling classes //c = (Alpha)c; //same as saying c=a } } This is what I think: 1)[ a=b ] will work because b is a subclass of a so its implicitly cast. 2)[ b=c ] needs explicit cast since its a downcast (compile error) 3) [ b = (Beta)a] should be ok since it is explicitly downcasted (no runtime error for me) 4) [ b = (Beta)c ] can't cast to sibling classes (compile error) 5) [ c = (Alpha)c] same as 2.. can't make c=a since that is a downcast So it looks like 1 and 3 will compile and run. And 2,4,5 are all compile time errors. Is this correct? Henry
|
not so smart guy still curious to learn new stuff every now and then
|
 |
henry wu
Greenhorn
Joined: Dec 01, 2000
Posts: 23
|
|
|
You're right.. I meant it to be b=a instead of b=c.
|
 |
Eric Cao
Greenhorn
Joined: Feb 26, 2002
Posts: 3
|
|
At line , there is no run time exception throwed, because you have called , then variable a actually refer to the object refered by b. [ March 12, 2002: Message edited by: Eric Cao ]
|
Eric Cao
|
 |
 |
|
|
subject: casting question
|
|
|