Search code examples
javacloneencapsulation

Java,cloning classes with access restrictions


I have :

  • class Personne implements Cloneable...

The personne class uses Adress class in it's field.

  • private Adresse adresse=ADRESSE_UNKNOWN;

So what i want is having a option to :

  • modify the cloned Person adress

    Here is my clone method :

    Object o = null;
    try {
    o = super.clone();
    } catch(CloneNotSupportedException cnse) {
      cnse.printStackTrace(System.err);
        }
        return o;
    } 
    
  • BUT that the original Person class won t have the access to the Cloned Person class Adress field.

Please give me a tip.


Solution

  • Ok Guys , so with help i understood. The possibility to override a clone() method is giving the opurtunity to modify the fields of the cloning class. As a proposed solution a reset the Adress field of the class to NULL. Then i created a setter that giving an option to modify the clone adress field.

        @Override
        public Personne clone()
    {
        Personne o;
        try {
           o = (Personne)super.clone();
           o.adresse = null;
           return o;
        } catch(CloneNotSupportedException cnse) {
          cnse.printStackTrace(System.err);
          throw new RuntimeException();
        }
    }
     // setter pour l adresse du Clone :
        public void setAdresseClone(Adresse a){
        this.clone().adresse = a;
        }