对于我的生活,我无法弄清楚这段代码有什么问题,请帮忙。我有三个类,GeometricObject,Octagon,它扩展了GeometricObject和TestOctagon,用于测试Octagon类。当我运行TestOctagon类时,我收到此错误:
Object类型的方法clone()不可见
这是我的代码:
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
protected GeometricObject() {
}
protected GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
import java.lang.Comparable;
import java.lang.Cloneable;
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable{
double side;
public Octagon() {
}
public Octagon(double side) {
this.side = side;
}
public Octagon(double side, String color, boolean filled) {
this.side = side;
setColor(color);
setFilled(filled);
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double getArea() {
return (2+4/Math.sqrt(2))*side*side;
}
public double getPerimeter() {
return 8*side;
}
@Override
public int compareTo(Octagon o) {
if (getArea() > o.getArea())
return 1;
else if (getArea() < o.getArea())
return -1;
else
return 0;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class TestOctagon {
public static void main(String[] args) {
// TODO Auto-generated method stub
GeometricObject oc1 = new Octagon(5);
System.out.println(oc1.getArea());
System.out.println(oc1.getPerimeter());
GeometricObject oc2 = (GeometricObject)oc1.clone();
}
}
答案 0 :(得分:0)
唐, 请注意,方法Object :: clone()的访问说明符受到保护。它不能从您的TestOctagon类访问,因为您在GeometriObject(oc1)类型的对象上调用此方法,其中克隆方法仍然受到保护,因为它或它的超类都没有覆盖它。尝试将clone方法从Octagon类移动到GeometriObject类。请保留公共访问说明符。请参阅此示例,了解如何执行此操作http://www.javatpoint.com/object-cloning