java中Cloneable与Serializable接口

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author huanghuankun
 */
public class CloneTest {

    public static class User implements Cloneable {//要设置为static类型,否则在static类型的main方法中不能引用

        String name;//引用类型
        int age;//primitive类型

        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

    }

    public static class CloneUser implements Cloneable {//继承Cloneable接口

        User user;
        long balance;

        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    public static void main(String[] args) {
        User user = new User();
        user.name = "huanghuankun";
        user.age = 25;
        CloneUser quoteUser = new CloneUser();
        quoteUser.user = user;//直接引用
        quoteUser.balance = 10000;
        try {
            CloneUser cloneUser = (CloneUser) quoteUser.clone();
            if (quoteUser.balance == cloneUser.balance) {
                System.out.println("因为balance是primitive类型,所以clone对象和原型是独立且相等的。");
            }
            quoteUser.balance = 20000;
            if (quoteUser.balance == cloneUser.balance) {
                System.out.println("改变任何primitive类型,不会影响原型的值");
            }
            if (quoteUser.user == cloneUser.user && quoteUser.user.equals(cloneUser.user)) {
                System.out.println("因为user是引用型对象,所以克隆对象的引用类型和原型对象的引用类型相等");
            }
            quoteUser.user.age = 24;
            if (cloneUser.user.age == 24) {
                System.out.println("所以改变引用类型的值,克隆对象和原型都会改变。");
            }
            User copyUser = (User)user.clone();
            copyUser.name = "huanghunkun1";
            if (!quoteUser.user.name.equals("huanghuankun1")) {
                System.out.println("String虽然是引用类型,但也是是不可改变类型,不能通过浅copy的方法来改变其值。");
            }
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(CloneTest.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Clone出现异常");
        }

    }
}

输出结果:

因为balance是primitive类型,所以clone对象和原型是独立且相等的。
因为user是引用型对象,所以克隆对象的引用类型和原型对象的引用类型相等
所以改变引用类型的值,克隆对象和原型都会改变。
String虽然是引用类型,但也是是不可改变类型,不能通过浅copy的方法来改变其值。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值