In your case, it's workable, but in some cases, it doesn't even work. Implementing a clone
method without calling super.clone
would make it impossible to make the subclass cloneable. For example, suppose I have a Fruit
class
public class Fruit implements Cloneable {
private String fruitName;
public Fruit(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitName() {
return fruitName;
}
public Fruit clone() {
return new Fruit(fruitName);
}
}
As you can see, I implement Fruit#clone
method without calling super.clone
, this seems fine. But now I want to create a class Apple
which extends Fruit
, like this:
public class Apple extends Fruit {
private String origin;
public Apple(String fruitName, String origin) {
super(fruitName);
this.origin = origin;
}
public Apple clone() {
// TODO
}
}
Now the problem is, how to implement Apple's clone
method. Should I call super.clone
inside Apple's clone
method? Yes, you should, otherwise you cannot get the value of fruitName
, which is a private field inside Fruit
. OK, let's try this:
public Apple clone() {
return (Apple) super.clone();
}
However, it didn't work. Because Fruit#clone
doesn't call super.clone
, so the result of super.clone()
inside Apple#clone
returns an instance of Fruit
instead of Apple
. Fruit
cannot be cast into Apple
, thus an error would be thrown:
Exception in thread "main" java.lang.ClassCastException: Fruit cannot be cast to Apple
at Apple.clone(Apple.java:20)
So as you can see, you cannot provide a workable clone
method for Apple
, whether you call super.clone
or not, it wouldn't work anyway. It's just because you didn't call super.clone
in Fruit#clone
.
In conclusion, you need to call super.clone
in the clone
method if you want the subclass to be cloneable.