Question

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?

Was it helpful?

Solution

yes you can downcast

((E)xyz).method();

OTHER TIPS

No, you cannot change the type of a variable after it is declared.

You can inline the typecasts, which saves some typing if you only need to downcast once:

Number n = 1;
((Integer)n).someIntegerMethod();

You should probably create a new variable if you need to do that more than once, though. The compiler may or may not be clever enough to optimize this properly otherwise (and you would incur the runtime overhead of repeated class casting).

if the parent class (O) had a method xyz as well, the you could just call

O xyz = new E();
xyz.method();   // E's xyz would be called

This is polymorphism

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top