-
Notifications
You must be signed in to change notification settings - Fork 7
/
SerialCloneTest.java
95 lines (83 loc) · 2.11 KB
/
SerialCloneTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.corejava.chapter1;
/**
@version 1.20 17 Aug 1998
@author Cay Horstmann
*/
import java.io.*;
import java.util.*;
public class SerialCloneTest
{
public static void main(String[] args)
{
MyEmployee harry = new MyEmployee("Harry Hacker", 35000, 1989, 10, 1);
MyEmployee harry2 = (MyEmployee) harry.clone();// clone harry
harry2.setName("copyHarry"); // mutate harry
// now harry and the clone are different
System.out.println("harry = " + harry);
System.out.println("harry2 = " + harry2);
}
}
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;
}
}
}
class MyEmployee extends SerialCloneable
{
private String name;
private double salary;
private Date hireDay;
public MyEmployee(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 void setName(String name)
{
this.name = name;
}
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
+ "]";
}
}