Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

java - The method clone() from object is not visible?

Question:

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

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.

'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.
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

clone() has protected access. Add this in MyClass

public Object clone(){  
    try{  
        return super.clone();  
    }catch(Exception e){ 
        return null; 
    }
}

Also Change to public class MyClass implements Cloneable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...