下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

Java中的克隆基础类会默认成什么

作者:课课家教育     来源: http://www.kokojia.com点击数:933发布时间: 2016-02-21 16:18:57

标签: Java基础类Java克隆Java编程

大神带你学编程,欢迎选课

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

Java中的克隆基础类会默认成什么_Java基础类_Java克隆_课课家

  //: 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以及它的所有“后裔”都可以克隆。

赞(17)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程