java clone protected,Object.clone()被保护的原因是什么?

本文探讨了在Java中使用`clone()`方法时遇到的问题。原始代码尝试直接调用`clone()`方法导致编译错误,因为`clone()`在`Object`类中是受保护的。解决方法是实现`Cloneable`接口并覆盖`clone()`方法。通过修改后的代码,展示了如何正确实现对象的深拷贝。此外,解释了`clone()`为受保护方法的原因,即防止只进行字段级别的浅拷贝而导致对象间的共享状态。
摘要由CSDN通过智能技术生成

Here is my test code for checking the clone method working,

class Test{

int a;

public void setA(int value){

a = value;

}

public int getA(){

return a;

}

}

class TestClass{

public static void main(String args[]){

Test obj1 = new Test();

obj1.setA(100);

Test obj2 = obj1.clone();

System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());

obj2.setA(9999);

System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());

}

}

Throws compilation error: clone() has protected access in java.lang.Object at obj1.clone()

What I am doing wrong here?

What is the reason behind clone() is protected?

Thanks

Edit along with Answer: Well at last I see my test harness is working when I implemented the Cloneable interface and overriden the clone method. It's not working with just overriding the clone() method from Object class. Here is the modified code,

class Test implements Cloneable{

int a;

public void setA(int value){

a = value;

}

public int getA(){

return a;

}

@Override

protected Test clone() throws CloneNotSupportedException{

return(Test) super.clone();

}

}

class TestClass{

public static void main(String args[]){

Test obj1 = new Test();

obj1.setA(100);

try{

Test obj2 = (Test)obj1.clone();

System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());

obj2.setA(9999);

System.out.println("obj1 A:"+obj1.getA()+" obj2 A:"+obj2.getA());

}catch(Exception e){

System.out.println("ERror"+e);

}

}

}

2. Reason for clone() method being protect: I found this from the book Core Java,

The clone method is a protected method of Object, which means that your code cannot simply call it. Only the Employee class can clone Employee objects.

There is a reason for this restriction. Think about the way in which the Object class can implement clone. It knows nothing about the object at all, so it can make only a field-byfield copy. If all data fields in the object are numbers or other basic types, copying the fields is just fine.

But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.

Hope this is helpful to others

解决方案

You should override the clone method in the Test class.

Why it is protected is discussed here although there doesn't seem to be a consensus.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值