-
damn clone()s
I have this chunk of code:
Code:
GameState [] tempGS = new GameState[7];
// for each of the moves a clean gamestate.
for ( int x=1; x<=6; x++)
tempGS[x] = state.clone();
Then my java compiler says:
Incompatible type for =. Can't convert Object to GameState.
Now I can read, obviously you can't convert GameState object to a GameState.clone() with the equals operator. So what did I do wrong? did I declare tempGS wrong, is there another way to get a copy of state (a GameState) into my array of GameStates?
Thanks!
NOMAD
ps: Yes, GameState is cloneable and no I did not write it (nor can I see it (only have class))
-
Did you try casting it?
Code:
tempGS[x] = (GameState)state.clone();
-
No, I hadn't, I tried it and it worked, thanks!
So .clone() not of the object it was made from... why is this, is casting it good code practise?
Thanks!
-
The reason casting was needed is because the clone() method is inherited all the way from the Object class. Since every class is inherited from the Object class, every class get the clone method.
So the return value of clone needs to be Object, so every class can use it. Your objects are still of the GameState type, but they are treated as general Object types for usabilities sake. You'll see the same type of behavior in collections. Collections hold values of type Object so that any class can be stored there.
:)