Overriding Methods

AP Computer Science A· difficulty 4/5

public class Box {
    private int v;
    public Box(int x) { v = x; }
    public boolean equals(Object o) {
        if (!(o instanceof Box)) return false;
        return v == ((Box) o).v;
    }
}
// Usage:
Box b = new Box(3);
System.out.print(b.equals(null));

What is printed?

  • A

    false

    check_circle
  • B

    true

  • C

    NullPointerException

  • D

    Compile error

Explanation

null instanceof anything is false, so the early return triggers and equals returns false. This is the safe pattern for handling null.

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

Related questions