File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Serialization and deserialization Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Serialization and deserialization" Watch "Serialization and deserialization" New topic
Author

Serialization and deserialization

Pinki Roy
Greenhorn

Joined: May 16, 2008
Posts: 14

I am not clear why the answer is A B A.

Someone please clarify it, please.


public class A {
public A() {
System.out.println("A");
}
}

public class B extends A implements Serializable {
public B() {
System.out.println("B");
}

}

public class Test {

public static void main(String... args) throws Exception {
B b = new B();

ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("datafile"));
save.writeObject(b);
save.flush();


ObjectInputStream restore = new ObjectInputStream(new FileInputStream("datafile"));
B z = (B) restore.readObject();



}

}



Astha Sharma
Ranch Hand

Joined: Oct 15, 2011
Posts: 128

Whe object is formed in line B b = new B(); construncors of both classes is called. It prints AB.
K&B -
If you are a serializable class, but your superclass is not serializable, then any instance variables you inherit from that superclass will be reset to the values they were given during the original construction of the object. This is because the non-serializable class constructor will run!
thus again constructor of superclass is called and A gets printed.
Sebanti Sanyal
Ranch Hand

Joined: Nov 07, 2011
Posts: 58

Wanted to mention a situation here when the non-serializable superclass does not have a no-arg constructor. De-serialization in that case will throw a run-time exception.
Mohamed Sanaulla
Bartender

Joined: Sep 08, 2007
Posts: 2694

Please UseCodeTags to post your code.


Mohamed Sanaulla | My Blog
Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 319
According to the practice exam book, it says object serialization and deserialization are removed from the exam objective for OCPJP 6.0 . But it is good to learn about it though.
 
 
subject: Serialization and deserialization
 
Threads others viewed
Serialization Doubt
doubt in reading object file
what is the flow of this program?
iteration
Serialization
developer file tools