来自对象的方法clone()不可见?

sek*_*har 45 java methods clone cloneable

题:

package GoodQuestions;
public class MyClass {  
    MyClass() throws CloneNotSupportedException {
        try {
            throw new CloneNotSupportedException();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }   

    public static void main(String[] args) {    
        try {
            MyClass  obj = new MyClass();
            MyClass obj3 = (MyClass)obj.clone();            
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的类'MyClass'可以通过调用'Object'类中的clone方法来克隆自己的对象.当我尝试在同一个包'GoodQuestions'中的另一个类('TestSingleTon')中克隆这个类('MyClass')时,它会抛出以下编译时错误.

'Object类型的方法clone()不可见 '

所以这是抛出上述错误的代码?

package GoodQuestions;
public class TestSingleTon {
    public static void main(String[] args) {
        MyClass  obj = new MyClass();
        MyClass obj3 = obj.clone(); ---> here is the compile error.
    }
}
Run Code Online (Sandbox Code Playgroud)

Eso*_*cMe 46

clone()有保护访问权限.添加此内容MyClass

public Object clone(){  
    try{  
        return super.clone();  
    }catch(Exception e){ 
        return null; 
    }
}
Run Code Online (Sandbox Code Playgroud)

也改为 public class MyClass implements Cloneable

  • 我假设protected modifier意味着包级别和子类.Java中的每个类都不是Object的子类吗?你的答案是对的,所以我在这里误解了什么? (5认同)
  • @Justin:是的,这意味着包级别和子类.因此,在你的子类"MyClass"中,它将是可见的.但它不会对"TestSingleTon"可见,它既不是同一个包也不是子类. (5认同)

小智 10

发生此错误是因为在Object类中clone()方法受到保护.所以你必须在各自的类中重写clone()方法.例如.在MyClass中添加以下代码

@Override
protected Object clone() throws CloneNotSupportedException {

    return super.clone();
}
Run Code Online (Sandbox Code Playgroud)

还实现了Cloneable接口.例如.public class MyClass implements Cloneable

  • 小心 return super.clone() 可能还不够 (2认同)