Writing Methods

AP Computer Science A· difficulty 3/5

public class ID {
    private int n;
    public ID(int n) { this.n = n; }
    public boolean equals(Object o) {
        if (!(o instanceof ID)) return false;
        return ((ID) o).n == this.n;
    }
}
// ...
ID a = new ID(7);
ID b = new ID(7);
System.out.println(a.equals(b));

What is printed?

  • A

    true

    check_circle
  • B

    false

  • C

    null

  • D

    Compile-time error

Explanation

The overridden equals compares the n fields, which are both 7, so it returns true.

Want 10 more like this — adaptive to your weak spots?

Related questions