Java 复制

未实现 Cloneable 接口的类调用 clone() 方法会抛出 CloneNotSupportedException 异常。


实例

class Employee implements Comparable<Employee>, Cloneable{





   String name;

   int age;





   public String getName() {

      return name;

   }





   public void setName(String name) {

      this.name = name;

   }





   public int getAge() {

      return age;

   }





   public void setAge(int age) {

      this.age = age;

   }





   public Employee() {};





   public Employee(String name, int age) {

      super();

      this.name = name;

      this.age = age;

   }





   public static String staticString() {

      return "static method.";

   }





   @Override

   public String toString() {

      return String.format("%s[name=%s, age=%d]", getClass().getName(), this.name, this.age);

   }





   @Override

   public int compareTo(Employee o) {

      return Integer.compare(this.age, o.age);

   }





   // 改成 public

   @Override

   public Object clone() throws CloneNotSupportedException {

      return super.clone();

   }

}


 

展开阅读全文