Search code examples
javainheritanceobjectpolymorphismdowncast

can you downcast objects in java without declaring a new variable?


I was trying to do something like

class O has a child E

I declare the variable

O xyz = new E();

but then if I call xyz.method(), I can only call those in class O's methods, not E's, so I can downcast it by

E xyz2 = (E) xyz;

My question is- Can you do this without declaring a new variable? Something like:

O xyz = new E();
xyz = (E) xyz; 

and now I can use xyz.method() to call E's methods

Is there a way to do this in java?


Solution

  • yes you can downcast

    ((E)xyz).method();