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

查看:138
本文介绍了来自对象的方法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()不可见 '

'The method clone() from the type Object is not visible'

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

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天全站免登陆