-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializationExamples3.java
60 lines (48 loc) · 1.6 KB
/
SerializationExamples3.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
package concept.examples.serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Actor {
String name;
Actor() {
name = "Default";
}
}
class Hero extends Actor implements Serializable {
String danceType;
Hero() {
danceType = "Default";
}
}
public class SerializationExamples3 {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
FileOutputStream fileStream = new FileOutputStream("Hero.ser");
ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
Hero hero = new Hero();
hero.danceType = "Ganganam";
hero.name = "Hero1";
// Before -> DanceType :Ganganam Name:Hero1
System.out.println("Before -> DanceType :" + hero.danceType + " Name:"
+ hero.name);
// Exception in thread "main" java.io.NotSerializableException:
// com.rithus.serialization.Wall
objectStream.writeObject(hero);
objectStream.close();
FileInputStream fileInputStream = new FileInputStream("Hero.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(
fileInputStream);
hero = (Hero) objectInputStream.readObject();
objectInputStream.close();
// When subclass is serializable and superclass is not, the state of
// subclass variables is retained. However, for the super class,
// initialization
// constructors and initializers are run again.
// After -> DanceType :Ganganam Name:Default
System.out.println("After -> DanceType :" + hero.danceType + " Name:"
+ hero.name);
}
}