2

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?

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
kamikaze_pilot
  • 14,304
  • 35
  • 111
  • 171
  • As @Leon points out, if you later (in the same scope) need `xyz` to be of type `E`, you would never write `O xyz = new E()`, but declare the proper type `E xyz = new E()`. But I assume that your real code is more difficult than this example. – Thilo Jan 31 '11 at 05:57

4 Answers4

7

yes you can downcast

((E)xyz).method();
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • This isn't what OP is asking though. OP is asking, "can I downcast and reassign back to the original variable?" Which is the same as asking "Can I redefine the type of a variable after declaration?" – Peter M. Elias Feb 09 '19 at 01:40
1

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).

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

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

Leon
  • 1,141
  • 13
  • 25
  • However, he said that this is not the case. Only the subclass has the method he wants to call. – Thilo Jan 31 '11 at 05:49
  • 1
    then he should just declare E xyz = new E() or create an an abstract method xyz in O. The the tag to this question is polymorphism and this would me polymorphic behaviour – Leon Jan 31 '11 at 05:51
  • 1
    That (declaring the variable to be of the type he actually needs) would be the best way. I am assuming that this is a simplified example, though. – Thilo Jan 31 '11 at 05:55
0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216