Overriding Methods

AP Computer Science A· difficulty 3/5

public class Point {
    private int x, y;
    public Point(int a, int b) { x = a; y = b; }
    public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }
}
// Usage:
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.print(a.equals(b));

What is printed?

  • A

    ClassCastException

  • B

    true

    check_circle
  • C

    Compile error

  • D

    false

Explanation

The equals override compares fields. b is a Point with x=1 and y=2 matching a, so equals returns true.

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

Related questions