Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning subclasses in Java

I need to clone a subclass in Java, but at the point in the code where this happens, I won't know the subclass type, only the super class. What's the best design pattern for doing this?

Example:

class Foo {
    String myFoo;
    public Foo(){}
    public Foo(Foo old) {
        this.myFoo = old.myFoo;
    }
}

class Bar extends Foo {
    String myBar;
    public Bar(){}
    public Bar(Bar old) {
        super(old); // copies myFoo
        this.myBar = old.myBar;
    }
}

class Copier {
    Foo foo;

    public Foo makeCopy(Foo oldFoo) {

        // this doesn't work if oldFoo is actually an
        // instance of Bar, because myBar is not copied
        Foo newFoo = new Foo(oldFoo);
        return newFoo;

        // unfortunately, I can't predict what oldFoo's the actual class
        // is, so I can't go:
        // if (oldFoo instanceof Bar) { // copy Bar here }
    }
}
like image 815
ccleve Avatar asked Dec 01 '10 21:12

ccleve


People also ask

What are the different types of cloning Java?

Cloning in Java can be grouped into two categories: Shallow Cloning. Deep Cloning.

What is cloning method in Java?

Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.

Is cloning allowed in Java?

Cloning is the process of creating a copy of an Object. Java Object class comes with native clone() method that returns the copy of the existing instance. Since Object is the base class in Java, all objects by default support cloning.

Which class contains clone method in Java?

Clone() Method This method belongs to the Object class, which is a base class of every class created in Java. This method helps to create a copy of the object, but if the class doesn't support a cloneable interface then it leads to the exception, " CloneNotSupportedException".


2 Answers

If you have control of the classes you are trying to copy, then a virtual method is the way forward:

class Foo {
    ...
    public Foo copy() {
        return new Foo(this);
    }
}
class Bar extends Foo {
    ...
    @Override public Bar copy() {
        return new Bar(this);
    }
}

(Ideally make classes either abstract or effectively final.)

like image 104
Tom Hawtin - tackline Avatar answered Sep 30 '22 07:09

Tom Hawtin - tackline


The most standard way in Java would be to make each class that may be cloned implement Cloneable, and override Object.clone() with a public version that does the cloning appropiately for that class (by default Object.clone() makes a shallow copy of the object).

Note that many people think that Cloneable/Object.clone() is bad design.

like image 32
gpeche Avatar answered Sep 30 '22 06:09

gpeche