Search code examples
javacloneextend

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){}
   }
}

Why does the Human class have to extend Main? If not, Human h2 = (Human)h1.clone() will give an error "The method clone() from the type Object is not visible"

What's the point for Human class to extend Main? Human class doesn't need to inherit anything from Main class.


Solution

  • Object.clone(); is protected, meaning it's visible to subclasses and classes in the same package. If you don't extend Main, clone() isn't visible since Human inherits it from Object (not visible to Main). However extending Main means that clone() is inherited from Main, which is in the same package, making it accessible.

    However normally you would implement a public version of clone(), even if to just call super.clone(); in it.