Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization among subclass

In interview it was ask that there is a Class A which does not implement the serializable interface as shown below

class A
{ 
    private int a;

    A( int a)
    {
        this.a = a;
    }
}

and there is a class B which extends A and also implements the serializable interface

class B extends A implements serializable
{

    private int a , b;

    B(int a, int b)
    {
        this.a = a;
        this.b = b; 
    }
}

Now please advise whether I can serialize class B or not , provided that class A is not serialized suppose I want to serialize the object of class B, can it be done.

like image 688
tuntun fdg Avatar asked Apr 02 '13 10:04

tuntun fdg


2 Answers

Is not possible to serialize B without modifying A to have an accesible no argument constructor.

From javadoc of java.io.Serializable

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable.

like image 173
dcernahoschi Avatar answered Sep 17 '22 22:09

dcernahoschi


Now please advise whether I can serialize class B or not , provided that class A is not serialized

Yes.

Any class which implement Serializable can be serialized. even if it's base class doesn't implement it.

All the classes extend Object which is not serializable but still it's sub-classes can be serialized by implementing Serializable.

like image 43
Azodious Avatar answered Sep 18 '22 22:09

Azodious