java object类中的clone_Java类中为什么不能直接调用Object的clone()方法

clone() 是protected的作用域。继承Cloneable接口后要重写方法,然后在方法里调用父类的clone()的方法。同时默认的克隆对于引用对象只是浅克隆。给你一段代码自己去运行试试吧:

package cesar.Test0810;

/**

* Created by Cesar on 2016/8/10.

*/

public class A implements Cloneable{

private int a;

private B b;

public int getA() {

return a;

}

public void setA(int a) {

this.a = a;

}

public B getB() {

return b;

}

@Override

public String toString() {

return "A{" +

"a=" + a +

", b=" + b +

'}';

}

public void setB(B b) {

this.b = b;

}

protected A clone() throws CloneNotSupportedException {

return (A) super.clone();

}

}

package cesar.Test0810;

/**

* Created by Cesar on 2016/8/10.

*/

public class B {

private int b1;

private int b2;

@Override

public String toString() {

return "B{" +

"b1=" + b1 +

", b2=" + b2 +

'}';

}

public B(int b1, int b2){

this.b1 = b1;

this.b2 = b2;

}

public int getB1() {

return b1;

}

public void setB1(int b1) {

this.b1 = b1;

}

public int getB2() {

return b2;

}

public void setB2(int b2) {

this.b2 = b2;

}

}

package cesar.Test0810;

/**

* Created by Cesar on 2016/8/10.

*/

public class TestClone {

public static void main(String[] args) {

A a = new A();

B b = new B(1, 2);

a.setA(10);

a.setB(b);

try {

A a1 = a.clone();

System.out.println("a=" + a.toString());

System.out.println("a1=" + a1.toString());

a.setA(1000);

a.getB().setB1(10000);

a.getB().setB2(8000);

System.out.println("a=" + a.toString());

System.out.println("a1=" + a1.toString());

a.setB(new B(9999,9999));

System.out.println("a=" + a.toString());

System.out.println("a1=" + a1.toString());

} catch (CloneNotSupportedException e) {

e.printStackTrace();

}

}

}

其中A继承了cloneable接口,同时持有了对B的引用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值