For your code to work, this code is either inside a SuperType class or subclass, or your SuperType type must have a public clone() method. The public clone() method does not exist automatically, and you must implement it. You could call it something else in this regard, for example. copy() .
The question then becomes how to implement this clone() method (or what to call it) so that it performs polymorphic cloning.
What was intended by the Java developers was to call super.clone() , assuming that all classes in the inheritance hierarchy are similarly implemented by clone() to perform polymorphic cloning. This ultimately comes to the protected Object.clone() method, which does the magic of polymorphic cloning. Note that for Object.clone() , in order not to throw an exception, your class must implement the Cloneable interface.
However, there are other possible methods. For example, assuming all subclasses have a default constructor, you can do something like this.getClass().newInstance() . This will create an object of the right class, but the fields will not be copied. Your clone method will have to copy all the fields, and subclasses will have to override your clone method to copy their fields, etc. Note that in this case it does not matter if the Cloneable interface is implemented.
Another way is that the class is Serializable, serialized and unserialize this . This should create a polymorphic clone that transfers all serializable fields.
source share