This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
why the following code will generate an runtime exception? ******************************************* public class CastTest{ public static void main(String[] args){ Base b = new Base(); Sub s = (Sub)b; } } class Base{} class Sub extends Base{} ******************************************* actually,Sub is subclass of class Base.why? 3x in advance
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
posted
0
At runtime, when this line is executed: Base b = new Base(); //line 1 The variable b contains a reference to an instance of type Base. In the next line, you try to assign that instance to a variable of type Sub. Sub s = (Sub)b; //line 2 However, the instance in b is NOT an instance of Sub, so the runtime system complains. If in line 1 above you had instead written Base b = new Sub(); then line 2 would not throw an exception , because when you cast b to a Sub, it is the correct type. Rob
Rob
SCJP 1.4
Arsho, Ayan
Ranch Hand
Joined: Nov 14, 2001
Posts: 60
posted
0
But if you declare it like this it will NOT throw out an runtime exception Base b = new Sub(); -Thanks [ January 14, 2002: Message edited by: Arsho, Ayan ]
Ragu Sivaraman
Ranch Hand
Joined: Jul 20, 2001
Posts: 464
posted
0
casting down gives a runtime exception.. class cast to be exact Ragu
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
posted
0
I can't help saying that if this were allowed, the instance of type Base could receive messages for which it is not prepared to response. They are the methods that were added in Sub but they don't exist in Base.
SCJP2. Please Indent your code using UBB Code
Axel Janssen
Ranch Hand
Joined: Jan 08, 2001
Posts: 2164
posted
0
This is another just-another-informal-explanation: For me it was easiest to remember if you think about is-a-relationship. Objects of class Sub is-a Base? Thats true!!! Objects of class Base is-a Sub? Thats NOT true!!! Class Sub is more than a Base. Its an extended Base. So you cant assign a class Sub reference variable to a class Base object. The other case is valid: You can assign a class Sub Object to a class Base reference variable, because a Sub-Object is-a (extended) Base object.