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 }
}
}
Cloning in Java can be grouped into two categories: Shallow Cloning. Deep Cloning.
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.
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.
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".
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With