2

Can i implement deep copy and shallow copy in following way?Is it correct? Any one on the following 2 clone methods would be placed in final code

public class Student{
  private String name;
  private DepartMent dept;


 //deep copy 
 public Object clone() throws CloneNotSupportedException{
  Student s =  (Student)super.clone();
  s.septDept((Department)dept.clone());
 }

 //shallow copy
 public Object clone() throws CloneNotSupportedException{
   return super.clone();
 }

}
user93796
  • 18,749
  • 31
  • 94
  • 150

3 Answers3

7

Instead of attempting to implement Cloneable, which is considered broken, I would recommend you look at using copy constructors. A copy constructor takes an instance of its own declaring type as an argument, and copies that instance's fields to the new object. For example:

public Student(Student copyFrom) {
    this.name = copyFrom.name;
    this.dept = copyFrom.dept;
}

...

Student copy = new Student(originalStudent);

If Department also exposes a copy constructor, this will allow you to make a deep copy of Student. For example:

public Student(Student copyFrom) {
    this.name = copyFrom.name;
    this.dept = new Department(copyFrom.dept);
}

Although it's unclear from your question why a deep copy is necessary.


For further reading, this article touches on both the issues of Cloneable and the limitations of copy constructors.

Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
0

As per my understanding it is right, only one thing that you have to make sure i.e. overriding of clone() method in DepartMent class also.

0

you could also use dup() method that also returns a copy of the original depends on what kind of code you are trying to implement with a copy method... you are just asking for advice without giving enough information to us to direct you correctly... There are also tons of answered questions in stackoverflow that has examples so you should've checked it with your stuff first before asking for additiona help

lifejuggler
  • 460
  • 6
  • 17