package com.io.SerialCloneTest;
/**
@version 1.20 17 Aug 1998
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
public class SerialCloneTest
{
public static void main(String[] args)
{
Employee harry = new Employee("Harry Hacker", 35000, 1989, 10, 1);
// clone harry
Employee harry2 = (Employee) harry.clone();
// mutate harry
harry.raiseSalary(10);
// now harry and the clone are different
System.out.println(harry);
System.out.println(harry2);
}
}
/**
A class whose clone method uses serialization.
*/
class SerialCloneable implements Cloneable, Serializable
{
public Object clone()
{
try
{
// save the object to a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
// read a clone of the object from the byte array
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object ret = in.readObject();
in.close();
return ret;
}
catch (Exception e)
{
return null;
}
}
}
/**
The familiar Employee class, redefined to extend the
SerialCloneable class.
*/
class Employee extends SerialCloneable
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
private String name;
private double salary;
private Date hireDay;
}
分享到:
相关推荐
深化理解JavaScript中的对象复制(Object Clone)_.docx
clone()方法示例(对象克隆)。作者: 初生不惑
本文实例讲述了PHP面向对象程序设计之对象克隆clone和魔术方法__clone()用法。分享给大家供大家参考,具体如下: 1.对象克隆 clone PHP4面向对象功能一个很大的缺点,是将对象视为另一种数据类型,这使得很多常见的...
JavaScript中并没有直接提供对象复制(Object Clone)的方法。因此下面的代码中改变对象b的时候,也就改变了对象a。 a = {k1:1, k2:2, k3:3}; b = a; b.k2 = 4; 如果只想改变b而保持a不变,就需要对对象a进行复制。 ...
C#中Clone一个对象的值到另一个对象案例 c#经典案例.pdf
java中clone的详细用法,分浅拷贝和深拷贝,并分别有详细的实例介绍。从原理分析。
深度克隆对象,不过效率没有显示的new对象快,不过很安全
javascript中clone对象详解.docx
git clone 最新版 不多说上资源 好用测试ok git clong git clone 最新版 不多说上资源 好用测试ok git clong
Clone 属性的相关内容 Clone 属性的相关内容
查看了很多文章对于clone()方法讲解都不慎透彻,特别是对于深层克隆的讲解语言晦涩难懂,很难理解,包括Oracle公司出版的JDK帮助文档也讲的不清楚,本人通过具体实践通过浅显易懂的语言详细讲解了clone()方法。...
在使用高版本版KEIL时,提示要升级固件,升级后就出现JLINK is Clone的提示!“the emulator is JLink-Clone, the segger software only support orginal segger device” 然后闪退,IDE崩溃关闭! 解决方案: 1....
Clone10-EX-LV2
主要介绍了Java利用序列化实现对象深度clone的方法,实例分析了java序列化及对象克隆的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
Jlink-clone解决办法,替换文件
Minesweeper CLone 0.97 Saolei.net扫雷网,小门汉化 Men Shiyun Mine.exe 请自行下载MinesweeperClone_0.97.exe安装后使用
java中clone的详细用法,分浅拷贝和深拷贝,并分别有详细的实例介绍。从原理分析。
详细的描述了Java中 clone方法使用
支持多个git库clone,提交等常用操作,用户需要根据实际情况微调参数