【java】对象克隆protected Object clone() throws CloneNotSupportedException

 1 package 对象克隆;
 2 class A implements Cloneable{//要具备clone()功能必须要实现Cloneable接口,此接口里无方法,只起标识作用。
 3     private String value;
 4     public A(String value){
 5         this.value=value;
 6     }
 7     public void setValue(String value) {
 8         this.value = value;
 9     }
10     @Override
11         public String toString() {
12             return "value="+value;
13         }
14     @Override
15     protected Object clone() throws CloneNotSupportedException {
16         return super.clone();
17     }//因为Object类里的clone方法是protected权限,所以要重写才能在主方法里调用。
18 }
19 public class Test_clone {
20     public static void main(String[] args) {
21         A a1=new A("我是A1");
22         A a2=null;
23         try {
24             a2=(A)a1.clone();
25         } catch (CloneNotSupportedException e) {
26             e.printStackTrace();
27         }
28         System.out.println(a1);//value=我是A1
29         System.out.println(a2);//value=我是A1
30         a1.setValue("a1->A1");
31         System.out.println(a1);//value=a1->A1
32         System.out.println(a2);//value=我是A1
33     }
34 }
View Code
原文地址:https://www.cnblogs.com/xiongjiawei/p/6679790.html