Wednesday 19 October 2016

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




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, 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.


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...