初学克隆,不懂。
下面代码、、
package 克隆矩形;
/**
*
* @author Administrator
*/
public class Rectangular {
int x1;
int x2;
int y1;
int y2;
int Sum;
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=(Rectangular)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.getMessage());
}
return o;
}
public int Sum()
{
Sum=((x2-x1)+(y2-y1))*2;
return Sum;
}
}
package 克隆矩形;
/**
*
* @author Administrator
*/
public class test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Rectangular r1 = new Rectangular(3,13,5,17);
Rectangular r2 = (Rectangular)r1.clone();
r2.x1=1; //到这里开始出错。
r2.x2=2;
r2.y1=7;
r2.y2=8;
System.out.println(r1.Sum());
System.out.println(r2.Sum());
}
}
我不知道什么原因,希望能解答一下,谢谢了
------解决方案--------------------
- Java code
public class Rectangular implements Cloneable {
------解决方案--------------------
你自己的Java类必须要声明实现Cloneable这个接口,然后对象执行clone方法的时候,才能给将属性正常克隆,不至于抛出CloneNotSupportedException
- Java code
/** * * @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()); }}