Saturday 9 April 2016

Effective Java Item 11: Cloneable interface

Cloneable determines the behavior of Object's protected clone implementation: if a class implements Cloneable, Object's clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException.

What does this sentence mean? Let's look at an example.

 class Dog implements Cloneable{  
   private String name;  
   private int age;  
   
   public Dog(String name, int age) {  
     this.name = name;  
     this.age = age;  
   }  
   
   @Override  
   public String toString() {  
     return "Dog{" +  
         "name='" + name + '\'' +  
         ", age=" + age +  
         '}';  
   }  
   
   @Override  
   public Dog clone() {  
     try {  
       return (Dog) super.clone();  
     } catch (CloneNotSupportedException e) {  
       e.printStackTrace();  
     }  
     return null;  
   }  
 }  
   
 public class MyClone {  
   public static void main(String[] args){  
     Dog dog = new Dog("dog",1);  
     System.out.println(dog.clone());  
   }  
 }  

It runs fine. Now take out the cloneable interface

The result is

 java.lang.CloneNotSupportedException: clone.Dog  
      at java.lang.Object.clone(Native Method)  
      at clone.Dog.clone(MyClone.java:22)  
      at clone.MyClone.main(MyClone.java:33)  
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)  
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  
      at java.lang.reflect.Method.invoke(Method.java:498)  
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)  
 null  

This says clone() method does not work without the Cloneable interface.

Effective Java Item 34 Generic T multiple extend

   interface IOperation{}  
   enum Operation implements IOperation{...}    
   private static <T extends Enum<T> & IOperation> void test(Class<T> opSet){  
     for (IOperation op : opSet.getEnumConstants()){  
       System.out.println(op);  
     }  
   }