Java 克隆方法不起作用
我似乎在catchJava 克隆方法不起作用,java,clone,Java,Clone,我似乎在catchCloneNotSupportedException中遇到了一个错误 public class Segment extends Point implements Cloneable { private Point p1, p2; public Segment() { this.p1 = new Point(); this.p2 = new Point(); } public Segment clone() {
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
就不会抱怨了。或者更简单,不要试图捕捉异常。它是Java
?您的点
类可克隆吗
?是的,它是Java,点类实现可克隆请放入cnse.printStackTrace()在你的中捕获并将结果添加(编辑)到你的问题中。我做到了。我仍在得到一份工作error@Avi,将您在问题中得到的异常的完整stacktrace添加为PM77-1,并说将您的Point类也包括在问题中。@Avi欢迎您,不要忘记接受答案。