clone() has protected access - made public Object clone()

不问归期 提交于 2019-11-30 00:44:57

问题


I'm writing code to create an object, clone the object, then compare the two.

The object in question, Octagon, is an extension of an object GeometricObject

public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable {
private double side;

public Octagon (double side){
    this.side = side;
}

public Object clone() throws CloneNotSupportedException {
    Octagon octClone = (Octagon)super.clone();
    return octClone;
}

In a file named Octagon.java

In another, TestOctagon.java, is my main method:

public class TestOctagon {
    public static void main(String[] args) {
        GeometricObject test = new Octagon(5); //create an Octagon with a side of 5
        System.out.println("Area is: "+test.getArea());
        System.out.println("Perimeter is: "+test.getPerimeter());

        Octagon copy = (Octagon)test.clone();


    }
}

The errors come in on the last line of the main method.

clone() has protected access in Object

I've tried renaming the clone method in Octagaon, say to cloneme, but then I get the error:

cannot find symbol
symbol: method cloneme()
location: variable test of type GeometricObject

I get the feeling the problem is because Octagon extends another object, maybe?

I really can't find any solution, and I've spent a good hour reading all the other clone() posts here.

Edit: It's required I use clone. I'm aware the general consensus is clone is borked.


回答1:


Replace

Octagon copy = (Octagon)test.clone();

with

Octagon copy = (Octagon)((Octagon)test).clone();

so that the called clone method is the one of your class.




回答2:


You may write a copy-constructor:

public Octagon( Octagon right ){
    this.side = right.side;
}

And use it from the clone method:

public Object clone() throws CloneNotSupportedException {
    return new Octagon( this );
}


来源:https://stackoverflow.com/questions/16044887/clone-has-protected-access-made-public-object-clone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!