When I run this code, I get ABA as output. I do not understand why he is typing A again

Below is the code below. In as a conclusion, but I did not understand the logic why A was printed again after B.

class A1 {
    public A1() {
        System.out.println("A");
    }
}

class B extends A1 implements Serializable {
    public B() {
        System.out.println("B");
    }

}

public class Test {

    public static void main(String... args) throws Exception {
        B b = new B();      // Object of class B
        ObjectOutputStream objout=new ObjectOutputStream(new FileOutputStream("t.txt"));
        objout.writeObject(b);

        ObjectInputStream objin=new ObjectInputStream(new FileInputStream("t.txt"));
        objin.readObject();
    }

}
+4
source share
5 answers

This explains that ctor B is not called again because it is serializable.

Reading an object is similar to starting the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are called for non-serializable classes.

A B new B(), ctor A, B. objin.readObject() ctor A A.

+4

super class subclass.

: object B , A1. objin.readObject() A.

Edit:

no-arg , . ? .

+1

A , A Serializable. :

Java: ?

+1

.

, B b = new B(); A- > B. A B


objin.readObject();

B-. ,

  • no-arg (i.e A1). A1 Serializable,

  • serializable (i.e B) . , B

, , A B A

doc

0

Java- ObjectInputStream ,

. (). No-arg , , , java.lang.object .

, B,

B b = new B();  // prints A B

A, B

,

objin.readObject();  // prints A as per docs

A, A , docs , , , No-arg.

, A B A

0
source

All Articles