answersLogoWhite

0

Imagine you want to save the state of one or more objects. If Java didn't have serialization, you'd have to use one of the I/O classes to write out the state of the instance variables of all the objects you want to save. The worst part would be trying to reconstruct new objects that were virtually identical to the objects you were trying to save. You'd need your own protocol for the way in which you wrote and restored the state of each object, or you could end up setting variables with the wrong values. For example, imagine you stored an object that has instance variables for height and weight. At the time you save the state of the object, you could write out the height and weight as two ints in a file, but the order in which you write them is crucial. It would be all too easy to re-create the object but mix up the height and weight values-using the saved height as the value for the new object's weight and vice versa.

The purpose of Serialization is to help us achieve whatever complicated scenario we just witnessed in an easier manner.

Serializing Objects

What does it really mean to save an object? If the instance variables are all primitive types, it's pretty straightforward. But what if the instance variables are themselves references to objects? What gets saved? Clearly in Java it wouldn't make any sense to save the actual value of a reference variable, because the value of a Java reference has meaning only within the context of a single instance of a JVM. In other words, if you tried to restore the object in another instance of the JVM, even running on the same computer on which the object was originally serialized, the reference would be useless.

But what about the object that the reference refers to? Look at this class:

class Car {

private Engine theEngine;

private int CarSize;

public Car(Engine Engine, int size) {

theEngine = Engine;

CarSize = size;

}

public Engine getEngine() { return theEngine; }

}

class Engine {

private int EngineSize;

public Engine(int size) { EngineSize = size; }

public int getEngineSize() { return EngineSize; }

}

Now make a Car... First, you make a Engine for the Car:

Engine c = new Engine(3);

Then make a new Car, passing it the Engine:

Car d = new Car(c, 8);

Now what happens if you save the Car? If the goal is to save and then restore a Car, and the restored Car is an exact duplicate of the Car that was saved, then the Car needs a Engine that is an exact duplicate of the Car's Engine at the time the Car was saved. That means both the Car and the Engine should be saved.

And what if the Engine itself had references to other objects-like perhaps a Color object? This gets quite complicated very quickly. If it were up to the programmer to know the internal structure of each object the Car referred to, so that the programmer could be sure to save all the state of all those objects. That would be a nightmare with even the simplest of objects.

Fortunately, the Java serialization mechanism takes care of all of this. When you serialize an object, Java serialization takes care of saving that object's entire "object graph." That means a deep copy of everything the saved object needs to be restored. For example, if you serialize a Car object, the Engine will be serialized automatically. And if the Engine class contained a reference to another object, THAT object would also be serialized, and so on. And the only object you have to worry about saving and restoring is the Car. The other objects required to fully reconstruct that Car are saved (and restored) automatically through serialization.

Remember, you do have to make a conscious choice to create objects that are serializable, by implementing the Serializable interface. If we want to save Car objects, for example, we'll have to modify the Car class as follows:

class Car implements Serializable {

// the rest of the code as before

// Serializable has no methods to implement

}

And now we can save the Car with the following code:

import java.io.*;

public class SerializeCar {

public static void main(String[] args) {

Engine c = new Engine(3);

Car d = new Car(c, 8);

try {

FileOutputStream fs = new FileOutputStream("testSer.ser");

ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(d);

os.close();

} Catch (Exception e) { e.printStackTrace(); }

}

}

But when we run this code we get a runtime exception something like this

java.io.NotSerializableException: Engine

What did we forget? The Engine class must ALSO be Serializable. If we modify the Engine class and make it serializable, then there's no problem:

class Engine implements Serializable {

// same

}

Here's the complete code:

import java.io.*;

public class SerializeCar {

public static void main(String[] args) {

Engine c = new Engine(3);

Car d = new Car(c, 5);

System.out.println("before: Engine size is "

+ d.getEngine().getEngineSize());

try {

FileOutputStream fs = new FileOutputStream("testSer.ser");

ObjectOutputStream os = new ObjectOutputStream(fs);

os.writeObject(d);

os.close();

} Catch (Exception e) { e.printStackTrace(); }

try {

FileInputStream fis = new FileInputStream("testSer.ser");

ObjectInputStream ois = new ObjectInputStream(fis);

d = (Car) ois.readObject();

ois.close();

} Catch (Exception e) { e.printStackTrace(); }

System.out.println("after: Engine size is "

+ d.getEngine().getEngineSize());

}

}

class Car implements Serializable {

private Engine theEngine;

private int CarSize;

public Car(Engine Engine, int size) {

theEngine = Engine;

CarSize = size;

}

public Engine getEngine() { return theEngine; }

}

class Engine implements Serializable {

private int EngineSize;

public Engine(int size) { EngineSize = size; }

public int getEngineSize() { return EngineSize; }

}

This produces the output:

before: Engine size is 3

after: Engine size is 3

User Avatar

Wiki User

14y ago

What else can I help you with?

Continue Learning about Engineering

What is an An address embedded in a file that links the file with an object?

It is poor programming practice resulting in undefined behaviour. Files should never store memory addresses (real or virtual), since there's no guarantee a valid object will always reside at the same location in memory, unless the programmer can be absolutely certain the object will outlive the file (such as when referring to active objects in memory via a temporary file).To embed an object in a file, the object must be stored in an independent file. The file in which the object is embedded simply links to the object's file. In this way, whenever the object is updated (and saved), all files in which it is embedded will also be updated.


What is object file?

In computer science, an object file is an organized collection of separate, named sequences of machine code.


Why program consists more than one object file in c?

why does a program consists of more than one object file in c++


Which method of object output streme class can be used to write the cotents of an object to a file?

write object


What is a jar file in java?

The Java.io.File class is an abstract representation of file and directory pathnames. Following are the important points about File:Instances may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system.A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

Related Questions

What is persistent object in c plus plus?

A persistent object is an object that retains its value between two different executions of the program that uses it. This means that some kind of disk file is used to store and load the object, using a method of the object, such as "serialize", to do so.


What is the best way to write an array to a file in PHP?

The serialize() function is used to create a storable representation of a variable in PHP.To store an array to a file, you first use the serialize() function to change an array into a string. Save the string in a file using file I/O, so fwrite() or a similar function. When reading it use unserialize() to get the original array again.


Can you serialize the ArrayList class in Java?

The ArrayList class itself is serializable and will serialize if it contains only serializable objects.If, however, you add non-serializable objects into the list then it will not serialize, but will throw a NotSerializableException.


Why embedded object documents requires more size than linked object?

Because a linked object is created and stored in a separate source file and then it is linked to the destination file, while an embedded object is created in a separate source file but then it is inserted into the destination file , becoming the part of that file.


Why embedded object document requires more size than linked object?

Because a linked object is created and stored in a separate source file and then it is linked to the destination file, while an embedded object is created in a separate source file but then it is inserted into the destination file , becoming the part of that file.


What is an An address embedded in a file that links the file with an object?

It is poor programming practice resulting in undefined behaviour. Files should never store memory addresses (real or virtual), since there's no guarantee a valid object will always reside at the same location in memory, unless the programmer can be absolutely certain the object will outlive the file (such as when referring to active objects in memory via a temporary file).To embed an object in a file, the object must be stored in an independent file. The file in which the object is embedded simply links to the object's file. In this way, whenever the object is updated (and saved), all files in which it is embedded will also be updated.


What is object file?

In computer science, an object file is an organized collection of separate, named sequences of machine code.


What is the difference between a form file object and a windows form object?

difference between a form file and a form.


What type of object is stored in its destination file?

a linked object


What is the difference between an executable file and a .class file?

Both are binary files but the differences between those are:- 1) we can execute an executable file while we cannot execute an object file. 2) An object file is a file where compiler has not yet linked to the libraries, so you get an object file just before linking to the libraries, so still some of the symbols or function definitions are not yet resolved which are actually present in the libraries, and that's why we cannot execute it. Once an object file is linked with the library by the compiler, then all the symbols are resolved and we get an executable file which can be executed on the appropriate platform. So basically the difference is that we get an object file when we don't link with library while executable file is with the linking phase. In gcc we can direct compiler not to link with library and so it will prepare the object file :- gcc -c test.c It will automatically create test.o object file when you try to execute it like:- ./test.o cannot execute binary file


Which type of object is stored only in its source file?

embedded object


What is the pathname in a URL?

A pathname is the location of a file or object in the context of a file system. A URL is the location of a file or object in the context of an internet web server.