I have seen the following 2 implementations of the Cloneable interface.
Example 1 : simply return super.clone();
class Employee1 implements Cloneable
{
private String name;
private int age;
private String address;
public Employee1(String name, int age, String address)
{
this.name = name; this.age = age; this.address = address;
}
public String getName() { return name; }
public int getAge() { return age; }
public String getAddress() { return address; }
public Object clone()throws CloneNotSupportedException
{
return (Employee1)super.clone();
}
}
Example 2 : explicitly assign each variable
class Employee2 implements Cloneable
{
private String name;
private int age;
private String address;
public Employee2(String name, int age, String address)
{
this.name = name; this.age = age; this.address = address;
}
public String getName() { return name; }
public int getAge() { return age; }
public String getAddress() { return address; }
public Object clone()throws CloneNotSupportedException
{
Employee2 emp2 = (Employee2)super.clone();
emp2.name = name;
emp2.age = age;
emp2.address = address;
return emp2;
}
}
Both are using either String or primitive types.
I can see if certain fields need to be calculated or possibly excluded but the objects I have seen will explicitly copy each individual attribute.
Are these two implementations identical?
Is it mostly a coding style which one prefers?
Any advantages or disadvantages to one over the other?