What will be the result of compiling and running the following code:

import java.io.*;

public class NewClass {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ObjectOutputStream oOut = new ObjectOutputStream(bOut);
        oOut.writeObject(new Sub()); 
        System.out.println("");
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        ObjectInputStream oIn = new ObjectInputStream(bIn);
        oIn.readObject();
    }
}

class Base {
    private int baseField = getInt(1);

    public Base() {
        System.out.print("Base.Base() ");
    }

    protected int getInt(int i) {
        System.out.print(i + " ");
        return i;
    }
}

class Sub extends Base implements Serializable {
    private int subField = getInt(2);

    public Sub() {
        System.out.print("Sub.Sub() ");
    }
}
Explanation
During deserialization of an object, that implements Serializable it's constructor is not executed and it's fields are not initialized with default values. But if serializable class extends non-serializable class, during it's deserialization an object of parent non-serializable class is created: it's fields are initialized by default and it's constructor is executed.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты