|
-
Feb 9th, 2003, 03:44 PM
#1
Thread Starter
Addicted Member
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))
-
Feb 9th, 2003, 04:04 PM
#2
Did you try casting it?
Code:
tempGS[x] = (GameState)state.clone();
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
-
Feb 9th, 2003, 04:12 PM
#3
Thread Starter
Addicted Member
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!
-
Feb 9th, 2003, 04:17 PM
#4
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.
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|