What is the output for the below code ? public class A { public A() { System.out.println("A"); } } public class B extends A implements Serializable { public B() { System.out.println("B"); } } public class Test { public static void main(String... args) throws Exception { B b = new B(); ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("datafile")); save.writeObject(b); save.flush(); ObjectInputStream restore = new ObjectInputStream(new FileInputStream("datafile")); B z = (B) restore.readObject(); } }

  1. A B A

  2. A B A B

  3. B B

  4. A B


Correct Option: A

AI Explanation

To determine the output of the given code, let's go through the code step by step:

  1. The code defines three classes: A, B, and Test.

  2. Class A has a default constructor that prints "A" when an object of class A is created.

  3. Class B extends class A and has a default constructor that prints "B" when an object of class B is created.

  4. In the main method of class Test, the following actions are performed:

    • An object b of class B is created, which invokes the default constructor of class B. This prints "A" and "B" in order.
    • An ObjectOutputStream save is created to write the object b to a file named "datafile".
    • The object b is written to the file using the writeObject method of ObjectOutputStream.
    • The ObjectOutputStream is flushed to ensure that all data is written to the file.
  5. An ObjectInputStream restore is created to read the object from the file "datafile".

  6. The readObject method of ObjectInputStream is used to read the object from the file and assign it to the variable z of class B.

Based on the code execution, the output will be "A B A".

Therefore, the correct answer is A) A B A.

Find more quizzes: