2
class Person implements Cloneable {
    int age;
    Person(int age) {
        this.age = age;
    }

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

public static void main(String[] args) {
    Person p = new Person(0);
    Person p1 = (Person) p.clone();
    p.age = 10;
    System.out.println(p.age + " " + p1.age);

}

the result is 10 0 In java, we can simply use the super.clone() to implement the clone. but how can I do the same thing in swift ? must I write something like this to implement the clone in swift ?

class Person: NSObject, NSCopying {
     var age: Int?

    func copyWithZone(zone: NSZone) -> AnyObject {
        var p = Person()
        p.age = self.age
        return p
    }
}

it seems ok with one class, one member. but if I has a lot of child class, and every child class has different members, it will be a lot of code, I should implement clone for every child class.

in java, only one clone method in superclass, it is much more simple.

JIE WANG
  • 1,875
  • 1
  • 17
  • 27

1 Answers1

2

In Obj-C, the correct way to copy objects is using the NSCopying protocol. In Swift, you should typically use a copy constructor although you can use NSCopying for classes that are derived from NSObject.

Yes, you have to write more code, however, clone in Java is one of the worst OOP problems in Java. It is not designed well. The fact that it decides what is going to be copied for you is not a good thing.

Also see How to properly override clone method?

In short, in Java, if you are implementing clone, you shouldn't call Object.clone. Implement the object creation using a constructor and decide by yourself what should be copied and how.

Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • why clone in java is one of the worst OOP problems ? could you explain in detail please ? – JIE WANG Jun 11 '15 at 09:09
  • @JIEWANG One of the most interesting problems is that it creates an object without invoking any constructors. The forced check for `Cloneable` is not nice either. There are many examples on the internet for `.clone` problems. Implementing `clone` using a private copy constructor is a nice idea. Of course, then you get exactly the same as is provided by `NSCopying`. – Sulthan Jun 11 '15 at 09:14
  • https://www.agiledeveloper.com/articles/cloning072002.htm @Sulthan thanks, I have read this article, and .clone seems not too bad if there is no static or final attribute in the class. – JIE WANG Jun 11 '15 at 12:33