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 metho
You can't create deep clone of abstract class because they can't be instantiated. All you can do is shallow cloning by using Object.clone() or returning this
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
or
@Override
public Object clone() throws CloneNotSupportedException {
return this;
}
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() as abstract and ask child class to define it, something like this
abstract class Shape {
private String str;
public Shape(String str) {
this.str = str;
}
public abstract Shape clone();
public String toString() {
return str;
}
}
class Circle extends Shape {
public Circle(String str) {
super(str);
}
@Override
public Shape clone() {
return new Circle("circle");
}
}