COMP2396
Loading...
Searching...
No Matches
notserialsuperclass.java
Go to the documentation of this file.
1// Serialized a serializable class with notSerializable superclass,
2// then deserialized it. The superclass fields are not serialized,
3// and instead called the no-argument Constructor
4
5import java.io.*;
6
7class notserializable {
8 public int var1;
9 transient Integer var1_1 = 2;
10 public notserializable() {
11 var1 = 10; // this no-argument constructor is called
12 // when deserializing the object
13 }
14}
15
16class serializableSubclass extends notserializable implements Serializable {
17 public int var2;
18 public serializableSubclass() {
19 var2 = 20;
20 }
21}
22
23@SuppressWarnings("unused")
24public class notserialsuperclass {
25 public static void main(String[] args) {
26 if (false) {
27 serializableSubclass a = new serializableSubclass();
28 a.var1_1 = 12; // modify the transient variable
29 a.var1 = 11;
30 a.var2 = 21;
31
32 try {
33 FileOutputStream fos = new FileOutputStream("test.file");
34 ObjectOutputStream oos = new ObjectOutputStream(fos);
35 oos.writeObject(a);
36 oos.close();
37 } catch (Exception ex) {
38 ex.printStackTrace();
39 }
40 } else {
41 serializableSubclass b = null;
42 try {
43 FileInputStream fis = new FileInputStream("test.file");
44 ObjectInputStream ois = new ObjectInputStream(fis);
45 b = (serializableSubclass) ois.readObject();
46 ois.close();
47 System.out.println(b.var1_1);
48 System.out.println(b.var1);
49 System.out.println(b.var2);
50 // output 2,10,21
51 // 2: transient variable default value, not serialized
52 // 10: no-argument constructor
53 // 21: var2 is serialized
54 } catch (Exception ex) {
55 ex.printStackTrace();
56 }
57 }
58 }
59}
static void main(String[] args)