1

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?

Unhandled Exception
  • 1,427
  • 14
  • 30
  • The "duplicate" article discusses the clone method but doesn't seem to discuss the main objective here which is the two different implementations. – Unhandled Exception Oct 03 '18 at 19:33
  • 1
    It does answer the question in the headline though. "When to add additional code to clone method?" Never, don't implement Cloneable. It's bad practice. https://stackoverflow.com/questions/3627053/speeding-up-java-deep-copy-operations/3627093#3627093 – Bakon Jarser Oct 03 '18 at 19:46

0 Answers0