[Java] to learn about some of the problems of the clone Object

1. Why Object clone modified in accessor is protected?

  First of all, protected role is to make itself and the method can only be called a subclass. deep copy clone object, if the class is copied contain other classes, must also be deep copy, as shown below

class Person{
  int salary;
  String name;
  Date birthDate;    
}

However, when the clone function when we called the Object, it had to ensure that this function is called an object class is a deep copy of the object class that contains only a shallow copy. At this time, if only the attribute type and comprising a base class object can not be modified Some (such as int and String), changing the value of a does not affect the value of b.

class Person{
  int salary;
  String name;
  Date birthDate;    

  public static void main(String[] args){
  Person a = new Person(12,"a",new Date());
  Person b = a.clone();
  }  

}

However, when we change the values ​​in the birthdate of a, b of the birthdate will change, which is clearly contrary to the original intention of the clone. Then we need to rewrite the clone, and access modifier changed into public, in order to access the outer class. So here arises the second question.

 

2. Why should we implement the interface Cloneable clone method of Object clone method instead of rewriting

In fact, the answers have been given above, in order to allow external class can access the clone method, we need to change the access modifier public. However, if the parent class is rewriting its access modifier can not be more than parent has access modifiers size range, it is not feasible.

 

Sentence summary: In order to achieve access to the outside world and can guarantee a deep copy clone method, we will set the Object clone protected and created the interface Cloneable

 

Guess you like

Origin www.cnblogs.com/Oliver1993/p/11470505.html