克隆方法不起作用

Clones method is not working

我似乎在捕获时出错 CloneNotSupportedException

public class Segment extends Point implements Cloneable {
    private Point p1, p2;

    public Segment() {
        this.p1 = new Point();
        this.p2 = new Point();
    }

    public Segment clone() {
        try {
            Segment cloned = (Segment) super.clone();
            cloned.p1 = (Point) p1.clone();
            cloned.p2 = (Point) p2.clone();
            return (cloned);
        } catch (CloneNotSupportedException cnse) { // This is the error
            cnse.printStackTrace();
            return null;
        }
    }
}


package myclasses;

public class Point implements Cloneable
{
private int x, y;

public Point()
{
    x = 0;
    y = 0;
}

public Point(int X, int Y)
{
    this.x = X;
    this.y = Y;
}

public int getX()
{
    return x;
}

public int getY()
{
    return y;
}

private void setX(int x)
{
    this.x = x;
}

private void setY(int y)
{
    this.y = y;
}

public void setPoint(int newX, int newY)
{
    getX();
    getY();

    setX(x);
    setY(y);
}

public void up(int i)
{
    y = getY() + i;
}

public void down(int i)
{
    y = getY() - i;
}

public void left(int i)
{
    x = getX() - i;
}

public void right(int i)
{
    x = getX() + i;
}

public String toString()
{
    return "(" + getX() + "," + getY() + ")";
}

public boolean equals(Object obj) 
{
    if (this == obj)
        return true;

    if (obj == null)
        return false;

    if (getClass() != obj.getClass())
        return false;

    Point that = (Point) obj;

    if (y != that.y)
        return false;

    if (x != that.x)
        return false;

    return true;
}

public Point clone()
{
    try
    {
        return (Point) super.clone();
    }       
    catch(CloneNotSupportedException cnse)
    {
        System.out.println(cnse);
        return null;
    }
}   
}

javac 报告的错误是

error: exception CloneNotSupportedException is never thrown in body of corresponding try statement
        } catch (CloneNotSupportedException cnse) { // This is the error

您可以这样声明 Point.clone()

public Point clone() throws CloneNotSupportedException

那么javac就不会抱怨了。或者更简单的不要尝试捕获异常。