public class Base{
protected String str;
public static final Base ERROR = new Base("error");
...
}
public class Derived extends Base{
public static final Derived OTHER = new DERIVED("other");
public Derived(String str) {
super(str);
}
}
Derived page = Derived.OTHER; //OK
page = (Drived)Derived.ERROR; //ClassCastException
So can I cast static member variable from Base to Derived class?
You can’t.
It is not possible to cast
Derived.ERRORtoDerivedsince it’s not an instance ofDerived. It’s an instance ofBase.It may help clear up the confusion to realize that
Base.ERRORandDerived.ERRORare two ways to refer to the same object.