2015-07-10 98 views
0

我似乎在捕獲CloneNotSupportedException出現錯誤。通過javac報道克隆方法不起作用

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

它是'Java'嗎?你的'Point'類是'Cloneable'嗎? –

+0

是的,它是Java和Point類實現Cloneable – Avi

+1

請在'catch'中放入'cnse.printStackTrace();'並將結果添加(編輯)到您的問題中。 –

回答

0

錯誤是

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

你可以這樣

public Point clone() throws CloneNotSupportedException 

聲明Point.clone(),然後javac不會抱怨。甚至更簡單,不要試圖捕捉異常。

+0

這很好。非常感謝您 – Avi

+0

@Avi歡迎您,不要忘記接受答案。 –