【问题标题】:Implementing clone method - Error java: clone() has protected access in java.lang.Object实现克隆方法 - 错误 java: clone() has protected access in java.lang.Object
【发布时间】: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 +
                '}';
    } }

【问题讨论】:

标签: java clone


【解决方案1】:

这是因为Circle cloned = (Circle) c2.clone(); 行您正试图访问它所定义的类之外的受保护成员。受保护的方法只能在同一个类或子类中调用。

如果你真的只想在 Main 类中访问它,然后重写 Circle 类中的 clone() 方法并使其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 Object clone() throws CloneNotSupportedException {
        // TODO: Your custom clone logic
        return super.clone();
    }

    @Override
    public String toString() {
        return "Circle{" +
            "center=" + center.toString() +
            ", radius=" + radius +
            '}';
    }
}

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多