Overriding Methods

AP Computer Science A· difficulty 2/5

public class Point {
    private int x, y;
    public Point(int a, int b) { x = a; y = b; }
    public String toString() {
        return "(" + x + "," + y + ")";
    }
}
// Usage:
Point p = new Point(3, 4);
System.out.print(p);

What is printed?

  • A

    Point@hashcode

  • B

    3 4

  • C

    Compile error

  • D

    (3,4)

    check_circle

Explanation

System.out.print on an object calls toString(). The overridden toString returns "(3,4)".

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

Related questions