0

Possible Duplicate:
Clone() vs Copy constructor- which is recommended in java

In below example,is there any difference between the objects created by useClone and copyConstrutor?

class A  implements Cloneable{
    int data = 9;
    public A useClone() throws CloneNotSupportedException  {
        return (A)super.clone();
    }
    public A copyConstrutor() {
        A o =  new A();
        o.data = this.data;
        return o;
    }
}
Community
  • 1
  • 1
Don Li
  • 1,095
  • 2
  • 12
  • 17
  • There is no 'copy constructor' either here or anywhere in Java. – user207421 Jun 17 '12 at 13:39
  • @EJP: A "copy constructor" is a constructor which takes a parameter of the same type as the new instance, and populates the new instance with the same data as the old. The code example given does not properly implement a copy constructor, but such constructors are pretty common. – supercat Jun 22 '12 at 16:44
  • Although your `copyConstructor` code will behave the same was as it would if it used a copy constructor, it does not actually use one. A copy constructor would be a constructor which takes an `A` as a parameter and sets the `this.data` to `param.Data`. The difference between using a copy constructor and using some other type of method is that a copy constructor can be used in the instantiation of a derived type instance, provided the required actual type is known by the code which invokes it. By contrast, your `copyConstructor` method cannot return anything other than an instance of `A`. – supercat Jun 22 '12 at 16:53
  • A proper implementation of a `clone()` method should return an object of the same type as the instance being cloned, whether or not the caller knows what that actual type is. If all parent implementations of `clone()` call `super.clone()` and then "patch up" the cloned object, then derived classes which don't add any new fields that would need patching up need not override `clone()` themselves. Any class derived or sub-derived from a class whose implementation of `clone()` uses a copy constructor, however, must supply its own override of `clone()`, which in turn must use a copy constructor. – supercat Jun 22 '12 at 16:57

0 Answers0