一个基本类:
package ddemo; public class A { private String str; private int count; public A(String str,int count){ this.str = str; this.count = count; } public A(){ } public String getStr() { return str; } public int getCount() { return count; } public void setStr(String str) { this.str = str; } public void setCount(int count) { this.count = count; } }
一个带有计数器的类:
package ddemo; public class Acount implements Cloneable { public static int count = 0; private int index; public Acount() { this.index = count; count ++; } public int getIndex(){ return index; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
一个带有copy函数的类:
package ddemo; public class Acopy { public static int count; private int index; private String str; public Acopy(){ this.index = count; count ++; } public Acopy(String str){ this.str = str; this.index = count; count++; } public String getStr(){ return this.str; } public int getIndex(){ return this.index; } public void setIndex(int index) { this.index = index; } public void setStr(String str) { this.str = str; } public Acopy copy(){ Acopy acopy = new Acopy(this.str); return acopy; } }
Demo:
package ddemo; /** * 这是一个测试类 * */ public class Demo1 { public static void main(String[] args) throws CloneNotSupportedException { A a1 = new A(); A a2 = a1; //1. 结果显示,a2只是a1的引用 System.out.println(a1); System.out.println(a2); //2. 一个每次实例化一个对象就计数的类 Acount acount1 = new Acount(); Acount acount2 = new Acount(); Acount acount3 = new Acount(); System.out.println(acount1.getIndex()); System.out.println(acount2.getIndex()); System.out.println(acount3.getIndex()); System.out.println(Acount.count); //2. 通过clone会绕开构造函数,从而使得计数器失效 Acount acount4 = (Acount) acount2.clone(); System.out.println(acount4.getIndex()); //3. 一个自带copy函数的类 System.out.println("=========================================="); Acopy acopy1 = new Acopy("Hello1"); Acopy acopy2 = new Acopy("Hello2"); Acopy acopy3 = new Acopy("Hello3"); Acopy acopy4 = acopy1.copy(); System.out.println(acopy1.getIndex()+acopy1.getStr()); System.out.println(acopy2.getIndex()+acopy2.getStr()); System.out.println(acopy3.getIndex()+acopy3.getStr()); System.out.println(acopy4.getIndex()+acopy4.getStr()); } }
result:
ddemo.A@4554617c ddemo.A@4554617c 0 1 2 3 1 ========================================== 0Hello1 1Hello2 2Hello3 3Hello1