Class not implements Cloneable will cause CloneNotSupportedException

本文通过两个测试案例,深入探讨了Java中实现克隆模式的方法和注意事项。首先,当类实现了Cloneable接口并正确覆盖clone方法时,可以成功创建对象的浅拷贝,修改拷贝对象不会影响原始对象。然而,若未实现Cloneable接口直接调用super.clone(),将抛出CloneNotSupportedException异常。本文旨在帮助读者理解克隆模式的正确使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The test case using jdk 1.8.

class C implements Cloneable

class C implements Cloneable {
    int id;

    public C(int id) {
        this.id = id;
    }
    @Override
    public C clone() throws CloneNotSupportedException {
        return (C)super.clone();
    }
}
public class CloneTest {

    @Test
    public void test1() throws CloneNotSupportedException {
        C c1 = new C(100);
        C c2 = c1.clone();
        System.out.println("c1:" + c1.id);
        System.out.println("c2:" + c2.id);
        c2.id = 101;
        System.out.println("c1:" + c1.id);
        System.out.println("c2:" + c2.id);
    }
}

Run the test case, it will print the following content.

c1:100
c2:100
c1:100
c2:101

Class not implements Cloneable

class C {
    int id;

    public C(int id) {
        this.id = id;
    }
    @Override
    public C clone() throws CloneNotSupportedException {
        return (C)super.clone();
    }
}
public class CloneTest {

    @Test
    public void test1() throws CloneNotSupportedException {
        C c1 = new C(100);
        C c2 = c1.clone();
        System.out.println("c1:" + c1.id);
        System.out.println("c2:" + c2.id);
        c2.id = 101;
        System.out.println("c1:" + c1.id);
        System.out.println("c2:" + c2.id);
    }
}

Run the test case, it will print the following content.


java.lang.CloneNotSupportedException: Item11.C

	at java.lang.Object.clone(Native Method)
	at Item11.C.clone(CloneTest.java:13)
	at Item11.CloneTest.test1(CloneTest.java:22)
	...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值