Jump to content

  • Log In with Google      Sign In   
  • Create Account






Send In The Java Clones !

Posted by Shippou, in Java 05 March 2014 · 334 views

Java
In Java whenever you want to copy an object's current state, you use the clone() method.
Simply using this does not work
     Object a = new Object();
     Object b = a; // <-- this creates a reference, not a copy 

Fortunately Java has built in methods for creating a perfect copy of your object's current state. Back in the old days clone() did not work so well, however as of Java 1.7 I have not had any issues with it.
.
Class A
.
public class Class_A {
    Class_B origional;
    Class_B clone;
    
    public Class_A(){
        origional = new Class_B(); // <--- Create a new object from Class B
        clone = origional.clone(); // <--- Call the class method to produce a clone
        clone.s = "World !"; // <--- set the clone's string to something else
        System.out.println(origional.getString() + " " + clone.getString() );
    }

}
.
Class B
.
public class Class_B implements Cloneable{ // <--- Class must implement Cloneable !!!
    
    int x;
    String s;
    Boolean b;
    
    public Class_B(){
        x = 1;
        s = "Hello"; // <--- Pay attention to this verable
        b = true;

    }
    public String getString(){return s;} // <--- Method returns the string verable
    
    public Class_B clone() { // <--- Method must have a try block !!!
	    try {
		    return (Class_B) super.clone(); // <--- Returns a clone of it's self
	    }
	    catch (Exception e) {
	        System.out.println("\n ===Error=== \n" + e + "\n" ); // <--- Always output errors
	        return null;}
	   }
} 





PARTNERS