Saturday, July 3, 2010

Java Cloning Examples


1. How to clone an Object/How to make a copy of an Object

package basics;

public class CloneExample {

// The Person value Object
class Person implements Cloneable {
private String name;
private Address address;

public Person(String name, String address) {
this.name = name;
this.address = new Address(address);
}

// Implementing cloning method
protected Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
clone.address = (Address) address.clone();
return clone;

}
}

// The Address value Object
class Address implements Cloneable {
String street = null;

public Address(String street) {
this.street = street;
}

// Implementing cloning method
protected Object clone() throws CloneNotSupportedException {
Address clone = (Address) super.clone();
return clone;
}

public String toString() {
return street;
}
}

void testCloning() {
try {
Person person = new Person("calvin", "redhill");
Person cloned = (Person) person.clone();
System.out.println(cloned.name);
System.out.println(cloned.address);

} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

CloneExample example = new CloneExample();
example.testCloning();
}
}

The out put will be:
calvin
redhill

No comments:

Post a Comment