Created
June 14, 2009 22:06
-
-
Save keithrbennett/129840 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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 CloneTestB { | |
| /** | |
| * 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(); } | |
| /** | |
| * Creates a new Foo, which will result in a new WrappedString | |
| * instance. Using super.clone(), you'd just get a reference | |
| * to the same WrappedString instance. | |
| * | |
| * @return the cloned object, or null if failed | |
| */ | |
| public Object clone() { | |
| return new Foo(getString()); | |
| } | |
| } | |
| 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 "mango" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment