Java OCA OCP Practice Question 2067

Question

Given the following code:.

public class Person {
 protected transient String name;
 Person() { this.name = "NoName"; }
 Person(String name) { this.name = name; }
}
public class Student extends Person {
 protected long studNum;
 Student() { }
 Student(String name, long studNum) {
   super(name);
   this.studNum = studNum;
 }
}
import java.io.*;

public class GraduateStudent extends Student implements Serializable {
  private int year;
  GraduateStudent(String name, long studNum, int year) {
     super(name, studNum);
     this.year = year;
  }//w  ww .  j a v a 2 s.c om

  public String toString() {
     return "(" + name + ", " + studNum + ", " + year  + ")";
  }

  private void readObject(ObjectInputStream ois)
               throws IOException, ClassNotFoundException {
      ois.defaultReadObject();
      name = "NewName";
      studNum = 200;
      year =2;
  }
}

import java.io.*;
public class Main {

  public static void main(String args[])
                      throws IOException, ClassNotFoundException {
    FileOutputStream outputFile = new FileOutputStream("storage.dat");
    ObjectOutputStream outputStream = new ObjectOutputStream(outputFile);
    GraduateStudent stud1 = new GraduateStudent("Java", 100, 1);
    System.out.print(stud1);/*from w w w. j  ava 2  s  . c o  m*/
    outputStream.writeObject(stud1);
    outputStream.flush();
    outputStream.close();

    FileInputStream inputFile = new FileInputStream("storage.dat");
    ObjectInputStream inputStream = new ObjectInputStream(inputFile);
    GraduateStudent stud2 = (GraduateStudent) inputStream.readObject();
    System.out.println(stud2);
    inputStream.close();
  }
}

Which statement about the program is true?

Select the one correct answer.

(a) It fails to compile.
(b) It compiles, but throws an exception at runtime.
(c) It prints (Java, 100, 1)(Java, 100, 1).
(d) It prints (Java, 100, 1)(NewName, 0, 1).
(e) It prints (Java, 100, 1)(NewName, 200, 2).


(e)

Note

Note that only GraduateStudent is Serializable.

The field name in the Person class is transient.

During serialization of a GraduateStudent object, the fields year and studNum are included as part of the serialization process, but not the field name.

During deserialization, the private method readObject() in the GraduateStudent class is called.

This method first deserializes the GraduateStudent object, but then initializes the fields with new values.




PreviousNext

Related