Tuesday, July 16, 2019

Object Serialization with Inheritance in Java

Case 1: If superclass is serializable then subclass is automatically serializable.
Answer:- If the superclass is Serializable, then by default, all its subclass is serializable. Even though subclass doesn't implement Serializable interface.

Case 2: If a superclass is not serializable then subclass can still be serialized
Answer:-
  • If super class is not Serializable than to serialize the subclass object. Then subclass must implement serializable interface explicitly. And in this case the superclass must have a no-argument constructor.
  • In this case no-argument constructor is called during the deserialization process. To initialize instance variables inherited from super class. Instance variabses of super calss will be set as default value.
  • If no-argument constructor is not present in super class (which not implements Serializable). Then it will throw Java.io.InvalidClassException: no valid constructor during deserialization process.
  • Note: If no-argument constructor is not present in super class (which not implements Serializable). Then it will serialize successfully but throw Exception during deserialization process.
java.io.InvalidClassException: com.javaiq.singletone.serialization.Child; no valid constructor
	at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:157)
	at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:862)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2034)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1567)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:427)
	at com.javaiq.singletone.serialization.MainTest.main(MainTest.java:39)
Printing value of Deserailized Child's instance :
Exception in thread "main" java.lang.NullPointerException
	at com.javaiq.singletone.serialization.MainTest.main(MainTest.java:56)
Example:
package com.javaiq.singletone.serialization;

public class Parent {

	String gender;
	int hight;

	public Parent() {

	}

	public Parent(String gender, int hight) {
		this.gender = gender;
		this.hight = hight;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public int getHight() {
		return hight;
	}

	public void setHight(int hight) {
		this.hight = hight;
	}
}


package com.javaiq.singletone.serialization;

import java.io.Serializable;

public class Child extends Parent implements Serializable {

	String name;
	int age;

	public Child(String gender, int hight, String name, int age) {
		super(gender, hight);
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

package com.javaiq.singletone.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainTest {

	public static void main(String[] args) {
		/*
		 * Assigning values to Man class's instance
		 */
		System.out.println("#######Start#######");
		Child child = new Child("Male", 5, "Sumit", 58);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream("serialObject.ser");
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(child);
			System.out.println("#######End#######");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		}

		/*
		 * Deserializing Man's instance
		 */
		Child childDser = null;
		try {
			FileInputStream fileInputStream = new FileInputStream("serialobject.ser");
			ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
			childDser = (Child) inputStream.readObject();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		} catch (ClassNotFoundException cnf) {
			// TODO Auto-generated catch block
			cnf.printStackTrace();
		}

		/*
		 * Printing values from deserialized Man's object
		 */
		System.out.println("Printing value of Deserailized Child's instance :");
		System.out.println("Gender: " + childDser.getGender());
		System.out.println("Hight: " + childDser.getHight());
		System.out.println("Name: " + childDser.getName());
		System.out.println("Age: " + childDser.getAge());
	}

}
Output:
Printing value of Deserailized Child's instance :
Gender: null
Hight: 0
Name: Sumit
Age: 58
As we can see in the output figure above ‘Gender’ and Hight gets a default value is null and 0 because of no default value set.
Case 3: If the superclass is serializable but we don’t want the subclass to be serialized
Answer:- To avoiding Serialization in sub-class we have to define writeObject() method and throw NotSerializableException() in sub-class.
private void writeObject(ObjectOutputStream os) throws NotSerializableException {
	     throw new NotSerializableException("This class cannot be Serialized");
	}
Calse 4: What happens if an object is serializable but it includes a reference to a non serializable object?
Answer:- it will be thrown 'NotSerializableException' at runtime.

Question: What is use of serialVersionUID?

Question: What are the changes to a serializable class can be compatible or incompatible ? 
Answer: 
Below is the list of changes which are compatible:
  • Add fields
  • Change a field from static to nonstatic
  • Change a field from transient to nontransient
  • Add classes to the object tree
Below list of incompatible changes:
  • Delete fields
  • Change class hierarchy
  • Change nonstatic fields to static fielsd
  • Change nontransient fields to transient fields
  • Change type of a primitive field
Question:  Can static variables saved as the part of serialization?
Answer:  No. As static variables belong to the class are not the part of the object so they are not saved as the part of serialized object.

Question: What is a transient variable?
Answer:  
  • Transient is a variables modifier used in serialization. which have a non-serialized value at the time of serialization.
  • Transient variables are not included in the process of serialization and are not the part of the object’s serialized state.
  • It will return default values after deserialization.
Question: What will be the value of transient variable after deserialization?
Answer: It will return default values after deserialization.

Question: When to add readObjectNoData() during serialization?

Question: What happens when a subclass class is serializable but its superclass is not?
Question:  How to Serializing Java Objects with Non-Serializable Attributes or reference?
Question:  How do you serialize a transient variable in Java?
Question:  Transient vs Static variable java?

Question: Serializing Objects into Database? or How to serialize object and store to database?
Answer: see here Serialize Object To Database
Question: How to serialize object and store into cache?
Answer:  see here Serialize Object And Store Into Cache
Question: How to serialize object and store into file?

No comments:

Post a Comment