Reputation: 1409
I know that this isn't a good idea, for a whole host of reasons, but if I have something like:
Dog s = new ShihTzu();
s.beCute();
Error: line 2 - cannot find symbol - method beCute()
((ShihTzu) s).beCute();
It's adorable!
In the same scope as Dog s
, can I permanently re-cast the variable name s
to be of type ShihTzu
?
Or is it completely impossible? Once a variable has been defined of a type, then, in its current scope, there's no way to change it?
Upvotes: 1
Views: 375
Reputation: 27159
No, it's not possible. When you declare a variable to be of a certain type, that can't be changed.
The Java spec says:
It is a compile-time error if the name of a formal parameter is used to declare a new variable within the body of the method, constructor, or lambda expression, unless the new variable is declared within a class declaration contained by the method, constructor, or lambda expression.
It is a compile-time error if the name of a local variable v is used to declare a new variable within the scope of v, unless the new variable is declared within a class whose declaration is within the scope of v.
Upvotes: 3