Cloneable接口的使用<Reprinted>

Cloneable接口声明中没有指定要实现的方法,一个类要实现Cloneable,最好是覆盖Object类的clone()方法。 


1. 如果类没有实现Cloneable接口,调用类对象的clone方法抛出CloneNotSupportedException。 

Java代码  收藏代码
  1. public class CloneableTest {  
  2.   
  3.     public static void main(String[] args) throws CloneNotSupportedException {  
  4.         CloneableTest test = new CloneableTest();  
  5.         Object obj = test.clone();  
  6.     }  
  7. }  



结果是抛出CloneNotSupportedException异常 


2. 我们无法定义一个类数组实现了Cloneable, 所以数组默认是实现了Cloneable接口。 

Java代码  收藏代码
  1. // Invalid definition  
  2. public class Person[] implements Cloneable  



Java代码  收藏代码
  1. int[] iMarks = new int[] { 471 , 8 };  
  2. int[] copyofiMarks = iMarks.clone();  



运行没问题。 


3. Object提供的clone方法是浅度复制 (shallow copy)。 

Java代码  收藏代码
  1. public class Name {  
  2.     private String firstName;  
  3.     private String lastName;  
  4.     // Omit the getters and setters as well as constructors  
  5. }  



Java代码  收藏代码
  1. public class Person implements Cloneable {  
  2.     private Name name;  
  3.     private int age;  
  4.     // Omit the getters and setters as well as constructors  
  5.   
  6.     protected Object clone() throws CloneNotSupportedException {  
  7.         return super.clone();  
  8.     }  
  9. }  



Java代码  收藏代码
  1. Name name = new Name("John""Chen");  
  2. Person person = new Person(name, 28);  
  3. Person copyOfPerson = (Person)person.clone();  
  4. name.setFirstName("Johnny");  
  5. name.setLastName("Qin");  
  6. person.setAge(29);  
  7. System.out.println(copyOfPerson.getName().getFirstName() + " " +  
  8.         copyOfPerson.getName().getLastName() +   
  9.         " " + copyOfPerson.getAge());  



结果是:Johnny Qin 28 

对于原型类型(如int),clone是没问题的,被clone的对象改变了不会影响到复制品(age还是28)。 

对于引用类型(如Name),clone方法只是复制了引用(浅度就体现在这),如果改变了引用的值,复制品也会受到影响(Johnny Qin)。 


4. 继承链上的祖先必须要有一个类声明实现Cloneable接口。 

Java代码  收藏代码
  1. public class Person {  
  2. }  



Java代码  收藏代码
  1. public class Male extends Person implements Cloneable {  
  2.     protected Object clone() throws CloneNotSupportedException {  
  3.         return super.clone();  
  4.     }  
  5. }  



Java代码  收藏代码
  1. public class ChineseMale extends Male {  
  2. }  



Java代码  收藏代码
  1. Person person = new Person();  
  2. Male male = new male();  
  3. ChineseMale chineseMale = new ChineseMale();  
  4. person.clone();  
  5. male.clone();  
  6. chineseMale.clone();  



person.clone()会报错。 


5. Object类本身没有实现Cloneable接口,在一个Object类对象上调用clone方法会报CloneNotSupportedException。

原文地址:https://www.cnblogs.com/xxx-xxx/p/3631945.html