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.
The clone() is protected because it is not declared in the Cloneable interface. Because of this reason, the clone method becomes somewhat useless as it might make the copies of your existing data.
clone() method is protected i.e. accessed by subclasses only. Since object is the parent class of all sub classes, so Clone() method can be used by all classes infact if we don't have above check of 'instance of Cloneable'.
The Java Object clone() method creates a shallow copy of the object. Here, the shallow copy means it creates a new object and copies all the fields and methods associated with the object. The syntax of the clone() method is: object.clone()
The clone() method is used to create a copy of an object of a class which implements Cloneable interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With