❮ Previous Next ❯

Serialization with respect to Inheritance

Case-1:-

Eventhough child class doesn’t implement serializable we can serialize child class object is parent class implements serializable interface that is serializable nature is inheriting from parent to child hence if parent is serializable then by default every child is serializable.

Example

import java.io.*;
class Animal implements Serializable
{
int i=10;
}
class Dog implements Animal
{
int j=20;
}
class SerializeDemo5
{
public static void main(String[] args)throws Exception
{
Dog d1=new Dog();
System.out.println(d1.i+"…"+d1.j);
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.WriteObject(d1);
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectOutputStream(fis);
Dog d2=(Dog)ois.readObject();
system.out.println(d2.i+"…"+d2.j);
}
}

In the above example eventhrough dog class doesn’t implement serializable we can serialize Dog object because its parent Animal class implements serializable.

Notes:

Object class doesn’t implement serializable interface.

Case-2:-

Example

import java.io.*;
class Animal
{
int i=10;
Animal()
{
System.out.println(“Animal constructor called”);
}
class Dog extends Animal implements Serilaizable
{
int j=20;
Dog()
{
System.out.println(“Dog constructor called”);
}
class SerializableDemo6
{
public static void main(String[] args)throws Exception
{
Dog d1=new Dog();
d2.i=888;
d2.j=999;
}
}
FileOutputStream fos=new FileOutputStream(“abc.ser”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
System.out.println(“Deserialization statred”);
FileInputStream fis= new FileInputStream(“abc.ser”);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+”….”+d2.j);
}
}
Output:
Animal constructor called
Dog constructor called
Deserialization started
Animal constructor called
0…..999
❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved