Cloning a rat

Remember, if you want to clone an object in Java, you should not follow HOWTOs on Google that try to answer your question with this piece of code:

public class Rat implements Cloneable {

public Object clone() {

Cloneable c = new Rat();
return c;
}

}

But instead, you should do that with the following snippet:

public class Rat implements Cloneable {

public Object clone() {

Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

return clone;

}

}

, because the first one does only create a new instance of Rat without the same internal state.

Leave a Reply