Originally posted by mikeliu:
Hi All,
Please help me clear the doubts.
What will happen if you attempt to compile and run the following code?
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
1.class Base {}
2.class Sub extends Base {}
3.class Sub2 extends Base {}
4.public class CEx{
5. public static void main(String argv[]){
6. Base b=new Base();
7. Sub s=(Sub) b;
8. }
9.}
I chose the 1, but the answer is 3. I am totally confused! because in RHE, it is ok to case the object reference at run time if one of classes must be a subclass of the other(it doesn't matter which one)(please refer to page118-119 in RHE if you have RHE). Am i missing something?
Mike
When I slove such questions,I first think about conversion then cast.
1. b is a class reference and it could only convert to its superclass.(RHE) Since it's illegal to convert to its sub class,
then it need cast.
2. As to cast,the compiler only check whether you have explict cast and it does not care who is base class and who is subclass.
(So if line 7 no (Sub) before b then it will generate compile error)
3. At the run time JVM will check the cast relationship between two classes.From RHE 118, since sub is a class, the class of the expression being converted must be sub or inherit from sub but base is super class, so it will generate run time exception.
Hope it will clear your doubt.
Kai,