cloning an object some of whose properties are objects

176 views Asked by At

I have a bit of a special exercise, here it is:

If an X object has a property that contains an object then a clone of the X object will contain in its property the same instance that the X object contained.

Modify the CloneMe class so that if an object of class CloneMe is cloned then the properties a and b of the object which are also objects are also cloned but the object contained in the property c is not cloned.

In other words, after cloning an object of class CloneMe, there should be two instances of class CloneMe containing two different instances of A and B, but referencing the same instance of C.

This is the code i have to complete:

class A implements Cloneable {
// clone functionality hidden
     }

     class B implements Cloneable {
// clone functionality hidden
     }

     class C implements Cloneable {
// clone functionality hidden
     }

     class CloneMe implements Cloneable {
         private A a;
         private B b;
         private C c;

         public CloneMe () {
             this.a = new A ();
             this.b = new B ();
             this.c = new C ();
         }

         public A getA () {return this.a; }
         public B getB () {return this.b; }
         public C getC () {return this.c; }

         / * ---------- DO NOT MODIFY THE CODE ABOVE THIS LINE, IT WILL BE RESET ON RUN ---------- * /

         / **** Enter your code here **** /

         / * ---------- DO NOT CHANGE THE CODE BELOW THIS LINE, IT WILL BE RESET WHEN RUNNING ---------- * /
     }

Here the code i completed:

 class CloneMe implements Cloneable {
        private A a;
        private B b;
        private C c;

        public CloneMe( ) {
            this.a = new A();
            this.b = new B();
            this.c = new C();
        }

        public A getA() { return this.a; }
        public B getB() { return this.b; }
        public C getC() { return this.c; }

        /*----------NE MODIFIEZ PAS LE CODE AU DESSUS DE CETTE LIGNE, IL SERA REINITIALISE LORS DE l'EXECUTION----------*/

        public Clone( ) {
        private A a=null;
        private B b=null;
        private C c=null;
           }

        /*----------NE MODIFIEZ PAS LE CODE EN DESSOUS DE CETTE LIGNE, IL SERA REINITIALISE LORS DE l'EXECUTION----------*/
    }

sorry, I haven't found a solution yet, the problem is that I don't quite understand this notion of clone, Do you have any leads for me please?

1

There are 1 answers

2
Thomas On

You have to implement the clone() method in CloneMe. This method has to initialize a, b and c calling the clone() method of A, B and C classes.