You get a runtime error because you are attempting to cast an object to an invalid type. That is, the object referenced by "base" is not of type Sub, so you cannot cast it to Sub.
The reason you get a runtime error and not a compile time error is it is possible for an object of type Base to also be of type Sub. The compiler cannot know whether or not the cast is valid. The validity of the cast can only be determined at runtime. If you attempt to cast an object to a type it does not implement or extend, you will get a ClassCastException.
Robert
Originally posted by venkataraman muthuvel:
my question is
interface I1 {}
interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Orange {
public static void main(String args[]) {
Base base = new Base();
I1 i1 = base; // 1
Sub sub = (Sub)base; // 2
}}
Result is Run-time error at line 2
any one explain this question why runtime error come at 2 properly casting
is done .
why runtime error come?
Base base=null;
then casting it would come any runtime error .
why?