• Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

Send In The Java Clones !

Sign in to follow this  


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;} }}
Sign in to follow this  


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement