Object Superclass

AP Computer Science A· difficulty 4/5

public class P {
    int x;
    public P(int x) { this.x = x; }
    public boolean equals(P o) { return o.x == this.x; }
}
Object a = new P(1);
Object b = new P(1);
System.out.println(a.equals(b));

What is printed?

  • A

    false

    check_circle
  • B

    true

  • C

    Compile-time error

  • D

    ClassCastException

Explanation

The custom equals takes P, but Object.equals takes Object. The custom method doesn't override; it overloads. Through Object reference, default equals (reference compare) is called.

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

Related questions