Jump to content
Sign in to follow this  
  • entries
    23
  • comments
    31
  • views
    55638

Send In The Java Clones !

Sign in to follow this  
RLS0812

987 views

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  


0 Comments


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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!