当前位置:天才代写 > tutorial > JAVA 教程 > 使克隆具有更大的深度

使克隆具有更大的深度

2017-11-13 08:00 星期一 所属: JAVA 教程 浏览:448

若新建一个类,它的基本类会默认为Object,并默认为不具备克隆本领(就象在下一节会看到的那样)。只要不明晰地添加克隆本领,这种本领便不会自动发生。但我们可以在任何层添加它,然后便可从谁人层开始向下具有克隆本领。如下所示:
 

//: HorrorFlick.java
// You can insert Cloneability at any
// level of inheritance.
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 InternalError();
    }
  }
}
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();
  }
} ///:~

添加克隆本领之前,编译器会阻止我们的克隆实验。一旦在Scientist里添加了克隆本领,那么Scientist以及它的所有“后代”都可以克隆。

 

    关键字:

天才代写-代写联系方式