This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Thursday, July 5, 2012

37 - to clone or not to clone

Try to understand the following :

package Object;

public class Customer implements Cloneable{

    private String firstName = "firstName";
    private String lastName = "lastName" ;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    Customer(String firstName, String lastName) {
        this.firstName  = new String(firstName);
        this.lastName = new String(lastName);
    }

    public Object getShallowCopy() throws CloneNotSupportedException{
        return this.clone();
    }

    public Object getDeepCopy() throws CloneNotSupportedException{
        return new Customer(this.firstName, this.lastName);
    }
}

package Object;

import org.junit.Test;
import static org.junit.Assert.*;

public class CustomerTest {

    @Test
    public void testClone() throws Exception {
        Customer customer = new Customer("rudy", "vissers");
        Customer clonedCustomer = (Customer)customer.getShallowCopy();
        assertTrue(customer != clonedCustomer);
        assertTrue(customer.getFirstName() == clonedCustomer.getFirstName());
        assertTrue(customer.getLastName() == clonedCustomer.getLastName());
        assertTrue(customer.getFirstName().equals(clonedCustomer.getFirstName()));
        assertTrue(customer.getLastName().equals(clonedCustomer.getLastName()));
    }

    @Test
    public void testDeepCopy() throws Exception {
        Customer customer = new Customer("rudy", "vissers");
        Customer deepCopy = (Customer)customer.getDeepCopy();
        assertTrue(customer != deepCopy);
        assertTrue(customer.getFirstName() != deepCopy.getFirstName());
        assertTrue(customer.getLastName() != deepCopy.getLastName());
        assertTrue(customer.getFirstName().equals(deepCopy.getFirstName()));
        assertTrue(customer.getLastName().equals(deepCopy.getLastName()));
    }

}

That's all folks !

Followers