来自对象的方法 clone() 不可见? [英] The method clone() from object is not visible?

查看:41
本文介绍了来自对象的方法 clone() 不可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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();
        }
    }
}

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

Here class 'MyClass' can able to clone its own object by calling the clone method in 'Object' class. When I try to clone the of this class('MyClass') in another class('TestSingleTon') in the same package 'GoodQuestions' it is throwing the following compile time error.

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

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

So here is the code it throwing the above error?

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

推荐答案

出现这个错误是因为在 Object 类中的 clone() 方法是受保护的.所以你必须在相应的类中覆盖 clone() 方法.例如.在 MyClass 中添加以下代码

This error occurs because in Object class clone() method is protected. So you have to override clone() method in respective class. Eg. Add below code in MyClass

@Override
protected Object clone() throws CloneNotSupportedException {

    return super.clone();
}

还实现了 Cloneable 接口.例如.公共类MyClass实现Cloneable

Also implement Cloneable interface. Eg. public class MyClass implements Cloneable

这篇关于来自对象的方法 clone() 不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆