Tuesday, 4 October 2016

Java Tutorial : Java IO (Java Serialization with HAS A Inheritance)

🚀 Level Up Your Java Skills!

If you found this helpful, click below to join our community for more simplified coding tutorials!

SUBSCRIBE TO RAM N JAVA

Understanding Java Serialization with HAS-A Relationship

In the world of Java programming, **Serialization** is the process of converting an object's state into a byte stream. This is crucial when you want to save an object to a file or send it over a network. But what happens when your class contains another class (a HAS-A relationship)? Let's break it down in a beginner-friendly way.

The Core Concept: Object Graphs

When you serialize an object, Java doesn't just look at the top-level class. It looks at the entire "object graph." If your class has a reference to another object (HAS-A), Java will attempt to serialize that referenced object as well.

The Golden Rule

For serialization to work smoothly in a HAS-A relationship, every object in the graph must be Serializable. If your main class implements the java.io.Serializable interface, but the class it "has" does not, Java will throw a NotSerializableException at runtime.

How to Handle Non-Serializable Members

Sometimes, you might have a member object that cannot be serialized (like a database connection or a file stream). In these cases, you have two main options:

  • Implement Serializable: Make the referenced class implement the Serializable interface.
  • Use the 'transient' Keyword: If you don't want or can't serialize a specific member, mark it as transient. Java will skip this field during the serialization process, and it will be initialized with its default value (like null for objects) during deserialization.

Key Takeaways for Beginners

  1. Serialization is recursive; it tries to save everything the object "owns."
  2. Always ensure nested objects are Serializable.
  3. Use transient to protect sensitive data or skip non-serializable components.

Check Out More Java Tutorials:

Explore these related topics from the Ram N Java channel to master Java IO:


Click here to watch in Youtube :
https://www.youtube.com/watch?v=6cE7lbJK7_U&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java IO (Java Serialization with HAS A Inheritance) 
Address.java
import java.io.Serializable;

public class Address implements Serializable
{
    private static final long serialVersionUID = 8899023823185198093L;
    private String streetName;
    private String city;
    private String state;

    public Address(String streetName, String city, String state)
    {
        super();
        this.streetName = streetName;
        this.city = city;
        this.state = state;
    }

    public String getStreetName()
    {
        return streetName;
    }

    public void setStreetName(String streetName)
    {
        this.streetName = streetName;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    @Override
    public String toString()
    {
        return "Address [streetName=" + streetName + ", city=" + city
                + ", state=" + state + "]";
    }

}
Employee.java
import java.io.Serializable;

/*
 * If a class has a reference of another class, all the
 * references must be Serializable otherwise
 * serialization process will not be performed. In such
 * case, NotSerializableException is thrown at runtime.
 * 
 * If Address is not Serializable, we cannot serialize
 * the instance of Employee class.
 */
public class Employee implements Serializable
{

    private static final long serialVersionUID = 765764534241652904L;
    private int id;
    private String name;
    private Address address; // HAS-A

    public Employee(int id, String name, Address address)
    {
        super();
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Address getAddress()
    {
        return address;
    }

    public void setAddress(Address address)
    {
        this.address = address;
    }

}
SerializationDemo.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializationDemo
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        SerializationDemo serializationDemo = new SerializationDemo();
        serializationDemo.writeEmployeeObject();
    }

    private void writeEmployeeObject() throws FileNotFoundException,
            IOException
    {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try
        {
            fileOutputStream = new FileOutputStream("employee.tmp");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);

            Address address = new Address("North Street", "Chennai",
                                                            "Tamil Nadu");

            Employee employee = new Employee(101, "Peter", address);

            /*
             * Write the specified object to the
             * ObjectOutputStream.
             */
            objectOutputStream.writeObject(employee);
            System.out
                    .println("Successfully written employee object to the file.\n");
        }
        finally
        {

            if (objectOutputStream != null)
            {
                /*
                 * Closing a ObjectOutputStream will also
                 * close the OutputStream instance to which
                 * the ObjectOutputStream is writing.
                 */
                objectOutputStream.close();
            }
        }

    }

}
Output
Successfully written employee object to the file.
employee.tmp


DeSerializationDemo.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeSerializationDemo
{

    public static void main(String[] args) throws FileNotFoundException,
            IOException, ClassNotFoundException
    {
        DeSerializationDemo deSerializationDemo = new DeSerializationDemo();
        deSerializationDemo.readEmployeeObject();
    }

    private void readEmployeeObject() throws IOException,
            FileNotFoundException, ClassNotFoundException
    {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;

        try
        {
            fileInputStream = new FileInputStream("employee.tmp");
            objectInputStream = new ObjectInputStream(fileInputStream);

            /*
             * Read an object from the ObjectInputStream.
             */
            Employee employee = (Employee) objectInputStream.readObject();

            System.out
                    .println("Successfully read employee object from the file.");

            System.out.println("Id  = " + employee.getId());
            System.out.println("Name = " + employee.getName());
            Address address = employee.getAddress();
            System.out.println("Address  = " + address);
        }
        finally
        {

            if (objectInputStream != null)
            {
                /*
                 * Closing a ObjectInputStream will also
                 * close the InputStream instance from which
                 * the ObjectInputStream is reading.
                 */
                objectInputStream.close();
            }
        }

    }

}
Output
Successfully read employee object from the file.
Id  = 101
Name = Peter
Address  = Address [streetName=North Street, city=Chennai, state=Tamil Nadu]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_Serialization_HAS_A_Relationship_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_Serialization_HAS_A_Relationship_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/9ef303db3f229fc70e7cf47baac5692282611e62/BasicJava/JavaIODemo_Serialization_HAS_A_Relationship_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment

    Tutorials