Adding cloneability
farther down a hierarchy
If you create a new class, its base class defaults to Object, which defaults to noncloneability (as you’ll see in the next section). As long as you don’t explicitly add cloneability, you won’t get it. But you can add it in at any layer and it will then be cloneable from that layer downward, like this:
//: appendixa:HorrorFlick.java
// You can insert Cloneability at any level of inheritance.
package appendixa;
import java.util.*;
class Person {}
class Hero extends Person {}
class Scientist extends Person implements Cloneable {
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
// This should never happen: It's Cloneable already!
throw new RuntimeException(e);
}
}
}
class MadScientist extends Scientist {}
public class HorrorFlick {
public static void main(String[] args) {
Person p = new Person();
Hero h = new Hero();
Scientist s = new Scientist();
MadScientist m = new MadScientist();
//! p = (Person)p.clone(); // Compile error
//! h = (Hero)h.clone(); // Compile error
s = (Scientist)s.clone();
m = (MadScientist)m.clone();
}
} ///:~
Before cloneability was added in the hierarchy, the compiler stopped you from trying to clone things. When cloneability is added in Scientist, then Scientist and all its descendants are cloneable.