Archived

This topic is now archived and is closed to further replies.

[java] copy one class to another?

This topic is 5148 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Im trying to copy one class into an array of classes for later use. My problem is that only my last monster (class) is the only one thats drawn?? Do I do anything wrong when I'm copying it:
for( int i=0; i<numMonstersPerLine; i++ ) {
	monsterperlevel[i] = new Monster();
}
for( int i=0; i<numMonstersPerLine; i++ ) {
	monsterperlevel[i] = monsterlist[1][1][0];
	monsterperlevel[i].body.yPos = 50;
	monsterperlevel[i].body.xPos = (i*50);
	monsterperlevel[i].body.visible = true;
}
------------------- Hans-Petter [edited by - Null and Void on November 12, 2003 4:53:22 PM]

Share this post


Link to post
Share on other sites
I think you''ve run into a problem with Java''s copy semantics. Every time you do monsterperlevel[i] = monsterlist[1][1][0] you''re making monsterperlevel[i] equal to a reference to the same thing monsterlist[1][1][0] is a reference to. I''m not really a Java programmer, but I would think people work around this by creating a method called copy in their classes that copies its member variables to another instance''s.

Random: You should use source tags to post code, so that your posts don''t get HTML-mangled. You should probably merge the two loops in the code too, since it would make sense .

Share this post


Link to post
Share on other sites
What you want to do is use the clone() method inherited from Object. You need to implement the Cloneable interface to be allowed to use it. Once you implement cloneable, you override clone and return a new reference to a monster object. Since clone returns an Object, you have to cast it to the correct class. Also you want to make sure you make a deep copy, not a shallow copy.

[EDIT]
Example of clone:

public class Monster implements Cloneable {
private int x;
private int y;
private Weapon weapon; //class you made

public Monster() {
.
.
.
}
public Object clone() {
Monster temp=new Monster();
temp.x=x;
temp.y=y;
temp.weapon=(Weapon)weapon.clone();//deep copy

//following would be a shallow copy

//temp.weapon=weapon;

//only copies the reference, does not create a new weapon

}
}



First make it work,
then make it fast.

--Brian Kernighan

The problems of this world cannot possibly be solved by skeptics or cynics whose horizons are limited by the obvious realities. We need men and women who can dream of things that never were. - John Fitzgerald Kennedy(35th US President)

Do not interrupt your enemy when he is making a mistake. - Napolean Bonaparte

[edited by - CaptainJester on November 13, 2003 7:24:43 AM]

Share this post


Link to post
Share on other sites