Das Verständnis für die Tiefe Kopie-Konstruktor in Java

Habe ich eine main-Klasse namens "Bar", ruft die Klasse Foo, und ich denke, dass ich in eine Tiefe Konstruktor korrekt

Dem Zweck, eine Tiefe Kopie-Konstruktor ist für das kopieren der Inhalte von einem Objekt zu einem anderen Objekt und ändern Sie das kopierte Objekt sollte nicht ändern Sie den Inhalt des ursprünglichen, richtigen?

Mein code das tut, aber ich verstehe nicht warum, wenn ich das original-Objekt-variable, die das kopieren Objekt nicht enthalten, die variable setzen, es enthält nur die default-Konstruktor variable.

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;
}
}
  • Konnte Sie zeigen, von wo Sie anrufen deepCopy?
  • Foo object2 = new Foo(object);
  • Ihre beschriebene symptom nicht passieren, dass ich mit diesem code.
  • sorry, ich fand den Fehler in meinem code, da ich kopiert und eingefügt die default-Konstruktor-argument in meinen tief Konstruktors und vergessen, es zu ändern name1
InformationsquelleAutor Dog | 2012-09-11
Schreibe einen Kommentar