Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Created June 14, 2009 22:02
Show Gist options
  • Select an option

  • Save keithrbennett/129839 to your computer and use it in GitHub Desktop.

Select an option

Save keithrbennett/129839 to your computer and use it in GitHub Desktop.
/**
* Shows a little about Object.clone()'s behavior.
*
* Object.clone() is a native method, so I couldn't look at the source code.
* I believe what it does is to copy object references. That means that
* if you don't override it, all clones will be pointing to the same
* instances of the contained members.
*/
public class CloneTestA {
/**
* Only purpose of this class is to contain
* a value that can be inspected.
*/
static class WrappedString implements Cloneable {
private String s;
public WrappedString() {}
public WrappedString(String s) { setS(s); }
public String getS() { return s; }
public void setS(String s) { this.s = s; }
}
/**
* This class' purpose is to contain an object that implements
* Cloneable, but does not override Object.clone()'s behavior.
*
* The result here is that
* both cloned objects will contain a reference to the same
* WrappedString. This is not always what you want; that's why
* in addition to implementing Cloneable, you usually would want
* to override Object.clone()'s behavior.
*/
static class Foo implements Cloneable {
private WrappedString wrappedString = new WrappedString();
public Foo(String s) { setString(s); }
public String getString() { return wrappedString.getS(); }
public void setString(String s) { wrappedString.setS(s); }
public String toString() { return getString(); }
/**
* Same behavior as Object.clone(); this is only here to make it public
*
* @return the cloned object, or null if failed
*/
public Object clone() {
Object newObject = null;
try {
newObject = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return newObject;
}
}
public static void main(String [] args) {
Foo f1 = new Foo("mango");
Foo f2 = (Foo) f1.clone();
f1.setString("durian");
System.out.println(f1); // prints "durian"
System.out.println(f2); // prints "durian" also
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment