我似乎在捕获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;
}
}
}
答案 0 :(得分:0)
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
不会抱怨。或者甚至更简单,不要试图捕捉异常。