I'm wondering if there is any way to do the following. I have an abstract class, Shape
, and all its different subclasses and I want to override the clone method. All I want to do in the method is create a new Shape
from the toString()
of the current one. Obviously I can't do the following because Shape
is abstract. Is there another way to do this because overriding clone in every subclass just for a simple name change seems useless.
public abstract class Shape {
public Shape(String str) {
// Create object from string representation
}
public Shape clone() {
// Need new way to do this
return new Shape(this.toString());
}
public String toString() {
// Correctly overriden toString()
}
}
You can try to use reflection:
}
in the clone() method you call getClass(). Because the ACloneble ist abstract, there call will allways go to the concrete class.
}
and
}
and finally
Output:
But it's more a hack than a solution
[EDIT] my two clones were faster than ;)
[EDIT] To be complete. Another implentation of clone() can be
when your abstract class implements Serialazable. There you write your object to disc and create a copy with the value from the disc.
Although I doubt it is a good idea, you could use reflection:
You can resolve with reflection:
but - IMO - is a poor implementation and error-prone with a lot of pits; the best use of
Cloneable
andObject.clone()
is to not use them! You have a lot of way to do the same thing (like serialization for deep-clone) and shallow-clone that allow your a better control of flow.You can't create deep clone of
abstract
class because they can't be instantiated. All you can do is shallow cloning by usingObject.clone()
or returningthis
or
An abstract class can act as a reference, and it cannot have an instance so shallow cloning works in this case
OR
As a better approach, you can declare
clone()
asabstract
and ask child class to define it, something like this