java中Cloneable与Serializable接口
来源:互联网 发布:java开发人员平均年龄 编辑:程序博客网 时间:2024/05/17 07:02
/* * 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
- java中Cloneable与Serializable接口
- Java中Serializable接口和Cloneable接口
- Java中 Cloneable 、Serializable 接口详解
- java的Cloneable、Serializable接口
- Java中Cloneable接口
- Java中Cloneable接口
- Java中Cloneable接口
- Java中Cloneable接口
- java中Cloneable接口
- Java中Cloneable接口
- Java Cloneable接口与Serializable接口实现对象克隆和深度克隆
- JAVA中clone()方法与Cloneable接口详细说明
- Java中Cloneable接口的用法
- Java中serializable接口
- Java对象克隆(Clone)及Cloneable接口、Serializable接口的深入探讨
- Java对象克隆(Clone)及Cloneable接口、Serializable接口的深入探讨
- Java对象克隆(Clone)及Cloneable接口、Serializable接口的深入探讨
- Java对象克隆(Clone)及Cloneable接口、Serializable接口的深入探讨
- 软件架构学习
- 若史蒂夫-科尔执教尼克斯,小斯将全力支持
- 启动文件、简单的消息框
- Algorithm学习笔记 --- 线段树单点更新
- 介绍一个c++检测内存泄露工具:Visual Leak Detector
- java中Cloneable与Serializable接口
- 计算机网络在电子商务中的应用研究
- powerDesigner学习一_概念模型
- Oracle Instance Client + PL/SQL Developer远程访问数据库(Windows)
- WEBAPP开发技巧总结
- ARP
- 用Android UEventObserver监听内核event
- 数据库更新操作方法一
- 网页中出现莫名其妙的空隙引号