Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Serializable Interface

 
Nick Ueda
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone please explain to me what the serializable interface is used for?
-Nick Ueda
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Serializable is a tagging interface, which means that it has no methods to implement. When your class implements Serializable, you are giving the VM permission to serialize any object of that class for persistence (like storing a file on your harddrive) or transmission across some wire protocol like RMI.
 
Gayathri Prasad
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Serialization allows you to create persistent objects, that is, objects that can be stored and then reconstituted for later use.Serializable interface is used to implement serialization. A small example would make more sense..
import java.io.*;
public class Person implements Serializable {
public String firstName;
public String lastName;
private String password;
transient Thread worker;
public Person(String firstName,
String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public String toString() {
return new String(
lastName + ", " + firstName);
}
}
class WritePerson {
public static void main(String [] args) {
Person p = new Person("Fred",
"Wesley", "cantguessthis");
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream(
"Person.ser"));
oos.writeObject(p);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (oos != null) {
try {oos.flush();}
catch (IOException ioe) {}
try {oos.close();}
catch (IOException ioe) {}
}
}
}
}
class ReadPerson {
public static void main(String [] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(
new FileInputStream(
"Person.ser"));
Object o = ois.readObject();
System.out.println(
"Read object " + o);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (ois != null) {
try {ois.close();}
catch (IOException ioe) {}
}
}
}
}
Person is a class that represents data you'd like to make persistent. You might want to archive it to disk and reload in a later session. Java technology makes this easy. All you need to do is declare that the Person class implements the java.io.Serializable interface. The Serializable interface does not have any methods. It's simply a "signal" interface that indicates to the Java virtual machine1 that you want to use the default serialization mechanism.
ATB,
Gaya3
-------------------------------------------------
Beginning is half done.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic