日期:2014-05-20 浏览次数:20807 次
public class Rectangular implements Cloneable {
------解决方案--------------------
你自己的Java类必须要声明实现Cloneable这个接口,然后对象执行clone方法的时候,才能给将属性正常克隆,不至于抛出CloneNotSupportedException
/** * * @author Administrator */ public class Rectangular implements Cloneable{ int x1; int x2; int y1; int y2; int Sum; public Rectangular(int x1,int x2,int y1,int y2) { this.x1=x1; this.x2=x2; this.y1=y1; this.y2=y2; } @Override public Object clone() { Object o=null; try { o=super.clone(); } catch(CloneNotSupportedException e) { // System.out.println(e.getMessage()); e.printStackTrace(); } return o; } public int Sum() { Sum=((x2-x1)+(y2-y1))*2; return Sum; } public static void main(String[] args) { Rectangular r1 = new Rectangular(3,13,5,17); System.out.println(""+r1.x1); Rectangular r2 = (Rectangular)r1.clone(); System.out.println(""+r2.x1); r2.x1=1; //到这里开始出错。 r2.x2=2; r2.y1=7; r2.y2=8; System.out.println(r1.Sum()); System.out.println(r2.Sum()); } }