Writing Methods

AP Computer Science A· difficulty 4/5

public class P {
    int x;
    public P(int x) { this.x = x; }
    public boolean equals(Object o) {
        if (!(o instanceof P)) return false;
        return ((P) o).x == this.x;
    }
}
System.out.println(new P(3).equals(new P(3)));

What is printed?

  • A

    false

  • B

    ClassCastException

  • C

    true

    check_circle
  • D

    Compile-time error

Explanation

The override compares the x fields, which are equal.

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

Related questions