import java.io.Serializable;
public class A {
int a1 = -1;
int a2 = -2;
int a3 = -3;
A() {
System.out.println("in A()");
}
}
package serialization2;
import java.io.Serializable;
public class A1 extends A implements Serializable {
int a;
transient int b;
A1(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
String aString = Integer.toString(super.a1)
+ " " + Integer.toString(super.a2)
+ " " + Integer.toString(super.a3)
+ " " + Integer.toString(a)
+ " " + Integer.toString(b);
return aString;
}
}
package serialization2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.imageio.stream.FileImageInputStream;
public class Main {
public static void main(String[] args) throws Exception {
A1 refA1 = new A1(-1,-2);
System.out.println("refA1 : " + refA1);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("A1.ser"));
oos.writeObject(refA1);
System.out.println("reading it back");
refA1 =(A1)new ObjectInputStream(new FileInputStream("A1.ser")).readObject();
System.out.println("refA1 : " + refA1);
}
}
If A is not serializable
run:
in A()
refA1 : -1 -2 -3 -1 -2
reading it back
in A()
refA1 : -1 -2 -3 -1 0
The constructor was called. b is transient and assigned 0.
If a is serializable
run:
in A()
refA1 : -1 -2 -3 -1 -2
reading it back
refA1 : -1 -2 -3 -1 0
The constructor was NOT called. b is still transient and still assigned 0.
No comments:
Post a Comment