2014-04-13 7 views
0

Shallow, Deep 및 Copy 생성자를 사용하여 Java 복제본을 시연하기 위해 하나의 테스트 응용 프로그램을 작성했습니다.Java 복제 얕은 복사본 복사 생성자 중첩 객체

나는 얕고 깊게 만들었지 만 복사 생성자로 나는 뭔가를 놓치고 있다고 생각한다.

아래 코드를보고 Copy 생성자 구현에 대한 수정 사항을 알려주십시오.

public class CopyConstructorDemo { 

    public static void main(String[] args) { 

     Teacher teacher = new Teacher("Kripalu"); 
     Student sOrg = new Student(15007, "Amit", "Chirimiri", teacher); 

     //Student sClo = sOrg;       //Java Reference 

     //Student sClo = (Student) sOrg.clone();  //CLONE 


     Student sClo = new Student(sOrg);    //COPY CONSTRUCTOR 

     sOrg.display(); 

     sClo.getTeacher().setName("ShriKrishn"); 

     sOrg.display(); 

    } 


} 

class Teacher implements Cloneable{ 

    String _name = ""; 

    Teacher(String name){ 
     this.setName(name); 
    } 

    String getName(){return _name;} 
    void setName(String name){_name = name;} 

    //For Deep copy 
    //@Override 
    protected Object clone(){ 

     try { 
      return super.clone(); 
     } catch (CloneNotSupportedException e) { 
      e.printStackTrace(); 
      return null; 
     } 

    } 
} 

class Student implements Cloneable{ 

    int _rollNo; 
    String _name; 
    String _address; 

    Teacher _teacher; 

    Student(int rollNo, String name, String address, Teacher teacher){ 
     this.setRollNo(rollNo); 
     this.setName(name); 
     this.setAddress(address); 

     _teacher = teacher; 
    } 

    Student(Student copyCons){ 
     this._rollNo = copyCons._rollNo; 
     this._name = copyCons._name; 
     this._address = copyCons._address; 
     this._teacher = copyCons._teacher; 

    } 

    Teacher getTeacher(){return _teacher;} 
    void setTeacher(Teacher teacher){_teacher = teacher;} 

    int getRollNo(){return _rollNo;} 
    String getName(){return _name;} 
    String getAddress(){return _address;} 

    void setRollNo(int rollNo){_rollNo = rollNo;} 
    void setName(String name){_name = name;} 
    void setAddress(String address){_address = address;} 

    void display(){ 
     System.out.println(_rollNo+" "+ 
          _name+" "+ 
          _address+" "+ 
          _teacher.getName()); 
    } 

    @Override 
    protected Object clone(){ 

     try { 

      //return super.clone();  //For Shallow copy 

      //For Deep copy 
      Student cloned = (Student)super.clone(); 
      cloned.setTeacher((Teacher)cloned.getTeacher().clone()); 
      return cloned; 

     } catch (CloneNotSupportedException e) { 
      e.printStackTrace(); 
      return null; 
     } 

    } 



} 

출력 (복사 생성자)

15,007 미트 Chirimiri Kripalu

15,007 미트 Chirimiri ShriKrishn

편집 :

학생 클래스가 중첩 포함하기 때문에 클래스 (교사) 참조 , 간단한 복사 생성자가 작동하지 않습니다. 우리는 학생 클래스의 복사 생성자와 함께 교사를위한 복제 (얕은 복사)를 사용하고 여기에 나머지 코드의

Student(Student copyCons){ 

    this._rollNo = copyCons._rollNo; 
    this._name = copyCons._name; 
    this._address = copyCons._address; 
    this._teacher = (Teacher) copyCons._teacher.clone(); //FIX: thanks to Amir 

} 

이 동일 변경된 복사 생성자입니다해야합니다.

답변

2

그의 복사 생성자 및 복제 방법은 어떻게해야 :

//Copy constructor for the student 
Student(Student copyCons){ 
    this._rollNo = copyCons._rollNo; 
    this._name = copyCons._name; 
    this._address = copyCons._address; 
    this._teacher = copyCons._teacher.clone(); 
} 

//Clone for the student 
protected Student clone(){ 
    return new Student(this); 
} 

교사의 경우 : 사용

//This is the copy constructor 
Teacher(Teacher t){ 
     setName(t.getName()); 
} 

//That's how you clone an object of type teacher 
protected Teacher clone(){ 
    return new Teacher(this); 
} 

예 :

학생을위한

Teacher t1 = new teacher("Teacher 1"); 
Teacher t1Clone = t1.clone(); 

Student s1 = new Student(15007, "Amit", "Chirimiri", t1); 
Student s1Clone = s1.clone(); 
+1

귀하의 clone 메소드는 Student as return 유형을 사용할 수 있습니다. 캐스트 – MTilsted

+0

\ @Amir를 피하려면이 작업을 수행해야합니다. 죄송하지만 코드를 가져 오지 못합니다. 내가 이미 복제와 함께 달성했다고 언급했듯이 이제는 복사 생성자로 복사해야합니다. 복사 생성자를 작성하고 새로운 Student (org)를 사용했습니다. 이제는 교사가 나에게 코드 스 니펫을 공유 할 수 있으며, 또한 어떻게 사용합니까? 나는 어디에서 새로운 교사 (org)를 부를까요 ... 모르겠다. –

+0

@AmitYadav 업데이트를 확인하십시오. – CMPS