Wednesday, July 11, 2012

I/O - Getting better understanding of API


Let's start with the class File


Notice that the file has not been created until the line 13 be reached, to memorize it think of when you create a File(line 10) it doesn't throw any exception but the method createNewFile does.

Serialization

Serialization is the mechanism that allows you save the state of objects.
Find below the keys to make a class serializable.


First of all we have to implement the interface serializable( look at line 11), also to save the state of object we need the classes FileOutputStream and ObjectOutputStream, the writeObject(object) method is responsible for it and to retrieve the serializable object from the file we need FileInputStream and ObjectInputStream the readObject() is responsible for reading it.

!Import

- If you don't want to save a member of object you must mark it as transient
- Whether a super class implements Serializable its subclasses are indirectly Serializable
- Whether a subclass implements Serializable and a superclass doesn't the constructor will be invoked as well as the instance variable will get their default values

Let's see an example:

Let's see what's been saved.



- if you wanna save a state of object that has a reference to another object which does not implement Serializable you have to write the methods writeObject() and readObject().


- Finally we can use serialization with static variables but as you've seen serialization is useful for objects

Print this post

No comments: