There is something that I don’t understand in the usual implementation of the clone method. If you look at the first line of a try block in the following code, we call super.clone (), which will create an instance of the superclass and return an Object reference to that instance. Now this instance does not necessarily contain findDay, so how do we say copy.hireDay? It is true that it will compile fine, but should it not crash if the instance does not contain findDay?
public Object clone() { try { Employee copy = (Employee) super.clone(); // copy ID, name, and salary! copy.hireDay = (Date) hireDay.clone(); return copy; } catch (CloneNotSupportedException e) { System.out.println(e); return null; } }
source share