I implemented this code:
class A {
//some code
}
class B extends A {
// some code
}
class C {
public static void main(String []args)
{
The reason it fails at runtime is that the object isn't a B. It's an A. So while some As can be casts as Bs, yours cannot.
The compilier just can't analyze everything that happened to your A object. For example.
A a1 = new B();
A a2 = new A();
B b1 = (B) a1; // Ok
B b2 = (B) a2; // Fails
So the compilier isn't sure whether your A object is actually castable to a B. So in the above, it would think that the last 2 lines were ok. But when you actually run the program, it realizes that a2
is not a B, it's only an A.