我有一个名为 Bar 的主类,它调用类 Foo,我想我正确地放入了一个深层构造函数
深层复制构造函数的目的是将一个对象的内容复制到另一个对象,并且更改复制的对象不应更改原始内容,对吗?
我的代码做到了,但我不明白为什么当我设置原始对象变量时,复制对象不包含该设置变量,它只包含默认构造函数变量。
public class Bar
{
public static void main(String[] args)
{
Foo object = new Foo();
object.setName1("qwertyuiop");
//the below line of code should copy object to object2?
Foo object2 = new Foo(object);
System.out.println(object.getName1());
//shouldn't the below line of code should output qwertyuiop since object2 is a copy of object? Why is it outputting the default constructor value Hello World?
System.out.println(object2.getName1());
//changes object2's name1 var to test if it changed object's var. it didn't, so my deep copy constructor is working
object2.setName1("TROLL");
System.out.println(object2.getName1());
System.out.println(object.getName1());
}
}
public class Foo
{
//instance variable(s)
private String name1;
public Foo()
{
System.out.println("Default Constructor called");
name1= "Hello World";
}
//deep copy constructor
public Foo(Foo deepCopyObject)
{
name1 = deepCopyObject.name1;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
}