Forums Register Login

casting question

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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

 
+Pie Number of slices to send: Send
You're right.. I meant it to be b=a instead of b=c.
+Pie Number of slices to send: Send
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 ]
What could go wrong in a swell place like "The Evil Eye"? Or with this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 665 times.
Similar Threads
Cast Question
Valiveru's Mock Exam: Question #7
Cast expression
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 22:57:36.