Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting question

 
henry wu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
henry wu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right.. I meant it to be b=a instead of b=c.
 
Eric Cao
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic