Object 类型的方法 clone() 不可见。扩展解决它

The method clone() from the type Object is not visible. Extend solves it

public class Human extends Main implements Cloneable{
    public String name;
    public Human(){};
    public Human(String input){
        this.name = input;
    }
}

import java.util.Scanner;
public class Main{
   public static void main(String[] args) {
      try{
         Scanner in = new Scanner(System.in);
         String input = in.next();

         Human h1 = new Human(input);
         Human h2 = (Human) h1.clone();

         System.out.println("Human original " + h1.name);
         System.out.println("Human clone " + h2.name);
         in.close();
      } catch(Exception e){}
   }
}

为什么 Human class 必须扩展 Main?如果不是,Human h2 = (Human)h1.clone() 会报错"The method clone() from the type Object is not visible"

Human class 扩展 Main 有什么意义? Human class 不需要从 Main class.

继承任何东西

Object.clone(); 受保护,这意味着它对同一包中的 sub类 和 类 可见。如果您不扩展 Mainclone() 将不可见,因为 HumanObject 继承它(对 Main 不可见)。然而,扩展 Main 意味着 clone() 继承自 Main,它们在同一个包中,使其可访问。

但是通常您会实现 clone()public 版本,即使只是在其中调用 super.clone();

Cloneableclone() 是 Java 早期版本的遗留设计错误;不要使用它们。

如果要创建实例的"clone",提供复制构造函数,然后自己复制字段:

public Human(Human other) {
  this.name = other.name;
}

Effective Java 中有一个项目详细描述了克隆的问题,以及为什么要避免它(还有 described here)。