can you downcast objects in java without declaring a new variable?-Collection of common programming errors
You cannot do it like this:
O xyz = new E();
xyz = (E) xyz;
xyx.someEMethod(); // compilation error
The reason is that typecasts of Java objects don’t actually change any values. Rather, they perform a type check against the object’s actual type.
Your code checks that the value of xyz is an E, but then assigns the result of the typecast back to xyz (second statement), thereby upcasting it back to an O again.
However, you can do this:
((E) xyx).someEMethod(); // fine
The parentheses around the typecast are essential, because the ‘.’ operator has higher precedence than a typecast.