Writing Methods

AP Computer Science A· difficulty 4/5

public class Point {
    private int x;
    public Point(int a) { x = a; }
    // Note the parameter type:
    public boolean equals(Point p) { return x == p.x; }
}
// Usage:
Object a = new Point(5);
Object b = new Point(5);
System.out.print(a.equals(b));

What is printed?

  • A

    ClassCastException

  • B

    true

  • C

    false

    check_circle
  • D

    Compile error

Explanation

The custom equals(Point) does NOT override Object.equals(Object); it only overloads. When a is declared Object, a.equals(b) calls Object.equals which compares references (false).

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

Related questions