Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 863
Dirgon Avatar asked Apr 16 '13 18:04

Dirgon


People also ask

Why is clone () protected?

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.

Why clone method is protected not public?

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

What is clone () in Java?

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

What is the use of clone () method?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface.


1 Answers

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.

like image 140
Denys Séguret Avatar answered Sep 23 '22 05:09

Denys Séguret