AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-basics: why constructor is not called during deserialization?

while doing desrialization constructor is not called why?

corejava x 352
basics x 170
Posted On : 2016-08-11 10:07:27.0
profile rahul patil - anyforum.in rahul patil
42-30
up-rate
-1
down-rate

Answers


Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization. While Serialization in java is a mechanism of writing the state of an object into a byte stream. Constructor will be called only at the time of object creation. Once you create an object and through serialization you save its state in a file, now this serialized object you can convert it into java object and can get the property whatever you set at the time of serialization.

Example of Java Serialization:
--------------------------------------------------------------------------
In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.

Student.java:
--------------------------------------
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}



Persist.java:
-------------------------------------
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(123,"ABC");

FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();
System.out.println("success");
}
}

Example of Java Deserialization:
-------------------------------------------------------------------------

Depersist.java:
------------------------------------
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{

ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);

in.close();
}
}

Output:
-------------------------------
123 ABC

Note:
----------------------
In Deserialization we convert the serialized object into java object. We don´t create any new object. It?s all about object state.

Posted On : 2016-08-11 22:00:23
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188221600
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in