The problem is that you're trying to downcast a ClassA
to a ClassB
, which isn't allowed because the actual object might be ClassX
(another subclass of ClassA
) which doesn't have an explicit conversion.
See the following example which will throw a ClassCastException
(but compiles just fine):
public class Main {
public static void main(String[] args) {
SubB var = (SubB) someMethod();
}
private static Super someMethod(){
return new SubA();
}
}
class Super { }
class SubA extends Super { }
class SubB extends Super { }
The code compiles perfectly:
someMethod()
returns a class of typeSuper
.SubA
extendsSuper
so the method definition isn't violatedSubB
extendsSuper
so it can cast an object of typeSuper
toSubB
Yet when you execute this, you'll try to cast an object of type SubA
to SubB
, which isn't possible.
Sidenotes:
- Don't use
ClassC
to name aninterface
- Put hierarchy in your classnames for small examples here (Super <-> Sub) instead of (A <-> B <-> C)