Overview:

Lesson 2 Serialization delves into the concept of object serialization in Java, a process that allows objects to be converted into a byte stream for storage or transmission. Serialization is crucial for saving and restoring the state of objects, especially when dealing with persistence or communication between different Java applications.

Key Concepts:

  1. Object Serialization:
    • Definition: Object serialization is the process of converting an object into a byte stream.
    • Purpose: Enables the storage or transmission of objects, preserving their state.
  2. Serializable Interface:
    • Definition: The Serializable interface is a marker interface in Java that indicates that the class can be serialized.
    • Purpose: Provides a way for the developer to explicitly state that an object can be serialized.
  3. ObjectOutputStream and ObjectInputStream:
    • ObjectOutputStream:
      • Usage: Used to write objects to an OutputStream, typically a file or a network connection.
      • Methods: writeObject(Object obj) is used to serialize an object.
    • ObjectInputStream:
      • Usage: Used to read objects from an InputStream, typically a file or a network connection.
      • Methods: readObject() is used to deserialize an object.

Example:

Let’s create a program that demonstrates object serialization in Java. We’ll define a simple class, Person, implement the Serializable interface, and then serialize and deserialize objects of this class.

import java.io.*;

class Person implements Serializable {
    private static final long serialVersionUID = 1L; // Required for versioning

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class SerializationExample {

    public static void main(String[] args) {
        // Serialize object
        Person person = new Person("Alice", 25);
        serializeObject(person, "person.ser");

        // Deserialize object
        Person deserializedPerson = (Person) deserializeObject("person.ser");
        System.out.println("Deserialized Person: " + deserializedPerson);
    }

    private static void serializeObject(Object object, String fileName) {
        try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName))) {
            outputStream.writeObject(object);
            System.out.println("Object serialized and saved to " + fileName);
        } catch (IOException e) {
            System.err.println("Error during serialization: " + e.getMessage());
        }
    }

    private static Object deserializeObject(String fileName) {
        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName))) {
            Object object = inputStream.readObject();
            System.out.println("Object deserialized from " + fileName);
            return object;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("Error during deserialization: " + e.getMessage());
            return null;
        }
    }
}

In this example, the Person class implements the Serializable interface, and objects of this class are serialized and deserialized using ObjectOutputStream and ObjectInputStream. Understanding object serialization is crucial when dealing with persistent storage or transmitting objects over a network.