Serialization between subclasses

In an interview, it was asked that there is a class Athat does not implement the interface serializable, as shown below

class A
{ 
    private int a;

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

and there is a class Bthat extends Aand also implements the interfaceserializable

class B extends A implements serializable
{

    private int a , b;

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

Now, please let me know if I can serialize the class Bor not, if the class is Anot serializable, suppose I want to serialize a class object B, this can be done.

+5
source share
6 answers

It is not possible to serialize B without changing A to have an accessible argument constructor without arguments.

From javadoc java.io.Serializable

, , , ( ) . , , no-arg . Serializable, . .

no-arg . no-arg , .

+4

, , , B , A

.

, Serializable, . .

Object, , Serializable.

+4

, , , , B .

+1

; B A.

Edit:

class A{
int a;
A(int t){
    a =t;
}
A(){}   //default constructor is must
 }

class B extends A implements Serializable{
String b;
B(int t, String u){
    super(t);
    b=u;
}
}

public class SOSerialization {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.ser"));
    B b = new B(1, "tmp");
    os.writeObject(b);
    os.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));

    Object o = ois.readObject();
    ois.close();
    B bb = (B)o;
    System.out.println(" values :"+ bb.a + "  "+ bb.b);
}
}

, .

:

: 0 tmp

, .

+1

.. B.. A, Serialization.

. .

0
source

of course you can serialize class B as it implements the Serializable interface.

1 . Any class that implements the Serializable interface can be serialized.

It doesn't matter if the base class is Serializable or not.

2 . If the base class is Serializable, then the subclass is also Serializable.

3 . If the object is serialized, then its complete graph of objects ends. All objects referenced by instance variables look at the object serialized.

0
source

All Articles