Return to site

JAVA CERTIFICATION QUESTION: Read and write objects by using serialization

· java

Given:

final class Item {
  String title;

  public Item(String title) {
    this.title = title;
  }

  String getTitle() {
    return title;
  }
}

class Order implements Serializable {
  private int id;
  private List<Item> items = new ArrayList<Item>();

  public Order(int id) {
    this.id = id;
  }

  public void addItem(Item i) {
    items.add(i);
  }

  public void getItem(int i) {
    items.get(i);
  }
}

Constraint: Item class code can't be modified.

Which of the following changes allows an order to be properly serialized?

A. Add this new method to the Order class:

private void writeObject(ObjectOutputStream s) throws IOException {  s.defaultWriteObject();
}

B. Add this new method to the Order class:

private void writeObject(ObjectOutputStream s) throws IOException {
  s.defaultWriteObject();
  for (Item itm : items) {
    s.writeObject(itm.getTitle());
  }
}

C. Add this new method to the Order class and mark the items instance variable transient:

private void writeObject(ObjectOutputStream s) throws IOException {
  s.defaultWriteObject();
  for (Item itm : items) {
    s.writeObject(itm.getTitle());
  }
}

D. None of the above

 

The answer is D.