On Marcus Green's Exam 1, question 17 says:
What will happen if you attempt to compile and run the following code?
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(
String argv[]){Base b=new Base();
Sub s=(Sub) b;
}
}
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
The answer was 3.
The reason:
Without the cast to sub you would get a compile time error. The cast tells the compiler that you really mean to do this and the actual type of b does not get resolved until runtime. Casting down the object hierarchy is a problem, as the compiler cannot be sure what has been implemented in descendent classes. Casting up is not a problem because sub classes will have the features of the base classes. This can feel counter intuitive if you are aware that with primitives casting is allowed for widening operations (ie byte to int).
I thought that as long as the casting made since you could would be able to explicitly cast down. Am I wrong. I am having problems and can't run the code.