62,614
社区成员
发帖
与我相关
我的任务
分享
public class CloneTest {
public static void main(String[] args) {
A a = new A();
A b = new A(3);
System.out.println(a.i);
System.out.println(b.i);
a = b.clone();
System.out.println(a.i);
b.i = 5;
System.out.println(b.i);
System.out.println(a.i);
}
}
class A implements Cloneable {
int i = 0;
A() {
}
A(int i) {
this.i = i;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/*
CloneTest.java:7: 不兼容的类型
找到: java.lang.Object
需要: A
a = b.clone();
^
1 错误
*/
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
A a = new A();
A b = new A(3);
System.out.println(a.i);
System.out.println(b.i);
a = (A)b.clone();//要强转
System.out.println(a.i);
b.i = 5;
System.out.println(b.i);
System.out.println(a.i);
}
}
class A implements Cloneable {
int i = 0;
A() {
}
A(int i) {
this.i = i;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public Object clone() throws CloneNotSupportedException {
//return super.clone();
//如果是浅克隆
return this; //直接返回对象本身
//如果是深克隆
//return new A(this.i); //重新生成一个对象,并用当前对象的属性初始化新对象
}
try{
a = (A)b.clone();
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
public class Test implements Cloneable
{
int a = 0;
public static void main(String[] args) throws Exception
{
Test t = new Test();
t.a = 123;
Test t1 = (Test) t.clone();
System.out.println(t1 == t);
System.out.println(t1.a);
}
@Override
public Object clone()
{
try
{
Test t = (Test) super.clone();
t.a = this.a;
return t;
}
catch (CloneNotSupportedException e)
{
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
}