package cn.hncu.program.construct;
import org.junit.Test;
/**
* 项目名:浅拷贝、深拷贝
* 时间 :2017-9-12 上午12:27:39
*/
public class Construct2 {
@Test
public void v1(){
Person p = new Person("Jack",new MyDate_(2017, 9, 12));
Person p2 = new Person(p,1);//----浅拷贝
System.out.println("p = "+p);
System.out.println("p2 = "+p2);
/*p = Person [name=Jack, birthday=MyDate [year=2017, month=9, day=12]]
p2 = Person [name=Jack, birthday=MyDate [year=2017, month=9, day=12]]*/
p2.setName("Rose");
p2.getBirthday().setYear(2018);/*必须通过获得MyDate对象来设置year*/
System.out.println("p = "+p);
System.out.println("p2 = "+p2);
/*p = Person [name=Jack, birthday=MyDate [year=2018, month=9, day=12]]
p2 = Person [name=Rose, birthday=MyDate [year=2018, month=9, day=12]]*/
}
@Test
public void v2(){
Person p = new Person("Jack", new MyDate_(2017, 9, 12));
Person p2 = new Person(p, "2");//----深拷贝
System.out.println("p = "+p);
System.out.println("p2 = "+p2);
p2.getBirthday().setYear(2018);//设置year --/*必须通过获得MyDate对象来设置year*/
p2.setName("Rose");//设置name
System.out.println("p = "+p);
System.out.println("p2 = "+p2);
/*birthday.setYear(2018);
p2.setBirthday(birthday);【注意】这种还是参与引用赋值了
不能通过这种方式设置值
*/
}
}
class Person{
private String name;
private MyDate_ birthday ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MyDate_ getBirthday() {
return birthday;
}
public void setBirthday(MyDate_ birthday) {
this.birthday = birthday;
}
public Person(String name, MyDate_ birthday) {
this.name = name;
this.birthday = birthday;
}
public Person() {
this("NoneName", null);
}
/*
* 参与深拷贝与浅拷贝的构造方法:
*/
public Person(Person p,int version){
this.name = p.name;
/*
* 浅拷贝:引用赋值必捆绑。
*/
this.birthday = p.birthday;
}
/*
* 深拷贝:把“引用赋值”转换成“基本数据类型或String类型”的数据赋值。
*
* 这里给this.birthday深拷贝赋值的最好的办法就是再new一个MyDate对象。
* this.birthday = new MyDate(p.brithday);
*/
public Person(Person p ,String version){
this.name = p.name;
this.birthday = new MyDate_(p.birthday);
}
@Override
public String toString() {
return "Person [name=" + name + ", birthday=" + birthday + "]";
}
}
class MyDate_{
private int year;
private int month;
private int day;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public MyDate_(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public MyDate_(MyDate_ d){
this(d.year, d.month, d.day);
}
public MyDate_(){
this(1970, 1, 1);
}
}
【Java概念】浅拷贝、深拷贝(7)
最新推荐文章于 2024-09-10 07:42:09 发布