Object Superclass

AP Computer Science A· difficulty 3/5

public class P {
    private 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;
    }
}
// ...
P a = new P(3);
String s = "3";
System.out.println(a.equals(s));

What is printed?

  • A

    false

    check_circle
  • B

    true

  • C

    Compile-time error

  • D

    ClassCastException

Explanation

Since s is not an instance of P, equals returns false at the first check.

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

Related questions