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
Although I doubt it is a good idea, you could use reflection:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) {
Square s1 = new Square("test");
Square s2 = (Square) s1.clone();
// show that s2 contains the same data
System.out.println(s2);
// show that s1 and s2 are really different objects
System.out.println(s1 == s2);
}
public static abstract class Shape {
private String str;
public Shape(String str) {
this.str = str;
}
public Shape clone() {
try {
Class> cl = this.getClass();
Constructor> cons = cl.getConstructor(String.class);
return (Shape) cons.newInstance(this.toString());
} catch (NoSuchMethodException | SecurityException |
InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
@Override
public String toString() {
return str;
}
}
public static class Square extends Shape {
public Square(String str) {
super(str);
}
}
}