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()); 
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        ObjectInputStream oIn = new ObjectInputStream(bIn);

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() ");
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.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Sign Up Now
or Subscribe for future quizzes