【发布时间】:2020-04-27 18:20:44
【问题描述】:
我正在编写这个小程序,但它有一个我找不到的错误。 我已经在互联网上搜索和阅读了几个小时,但我不断收到相同的错误消息:java:clone() has protected access in java.lang.Object。 我正在尝试在 Point 上实现方法 clone(),以便在执行 Main 后只有 c1 执行 moveTo。 谁能告诉我是什么问题以及如何解决?
public class Main {
public static void main(String[] args) {
Point p = new Point(5,7);
Circle c1 = new Circle(p, 3);
Circle c2 = new Circle(p, 5);
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
c1.moveTo(2,3);
Circle cloned = (Circle) c2.clone();
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
} }
public class Circle {
public final Point center;
public final int radius;
public Circle(Point center, int radius) {
this.center = center;
this.radius = radius;
}
public void moveTo(int x, int y){
center.setX(x);
center.setY(y);
}
@Override
public String toString() {
return "Circle{" +
"center=" + center.toString() +
", radius=" + radius +
'}';
} }
public class Point implements Cloneable{
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
} }
【问题讨论】: