深克隆作业:
package hrkj;
import java.util.Arrays;
/**
*深克隆类 <br>
* 2019年11月30日 上午8:58:48
*
* @author 小原
* @version 1.0
*/
public class CloneTest {
/**
*程序的入口
* @param args 入口参数
* @throws CloneNotSupportedException 抛出异常
*/
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address(18);
Address address2 = address.clone();
//此处输出flase代表不是指向同一个地址
System.out.println(address.a == address2.a);//FLASE
System.out.println("年龄:" + address.age + "\n" + address2.a);
System.out.println(address==address2);//flase
}
}
class Address implements Cloneable {
int age;
Use a;
public Address(int age) {
// TODO Auto-generated constructor stub
super();
this.age = age;
this.a = new Use("陈兵杰",new int[] {1,2,3,4,5}) ;
}
@Override
protected Address clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Address address = (Address) super.clone();
address.a = a.clone();
return address;
}
}
class Use implements Cloneable {
String nameString;
private int[] b;
public Use(String nameString,int[] a) {
// TODO Auto-generated constructor stub
super();
this.nameString = nameString;
this.b=a;
}
/**
* 获取
*
* @return the nameString
*/
public String getNameString() {
return nameString;
}
/**
* 设置
*
* @param nameString the nameString to set
*/
public void setNameString(String nameString) {
this.nameString = nameString;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "名字:" + getNameString()+"\n数组:"+getB();
}
/**
*获取b数组
* @return the a
*/
public String getB() {
return Arrays.toString(b);
}
/**
*设置b数组
* @param a the a to set
*/
public void setB(int[] a) {
b = a;
}
@Override
protected Use clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return (Use) super.clone();
}
}