Suppose I am using a third party project with a Class A in it. And Class A is used everywhere. Inside Class A, I am not happy with Method M1. Firstly, I don't wanna change Class A, secondly, I need A.M1() know about something in the context. (M1 will be called by other) My design would be:
public MyClass {
ContextInfo ci;
public class B extends A {
//@Override M1() {use ci}
}
//Somehow I have a stack of A,
//and I know this is the only places A objects will be in
Stack<A> s = getStack();
//Now I wanna replace the top of the stack. or I can convert all As to Bs in the stack
A a = s.pop();
B b = (B) a; //here it fails
s.push(b);
}
Since I am downcasting, I have run time casting error. Is there a way for the compiler or JVM to realize that B can only do what A is allowed to do (not strictly a subtype) so that this should not be a problem? Or some other ideas to solve the problem?