AP Computer Science A · Topic 9.3
Overriding Methods Practice
Part of Inheritance.
Practice questions
27
Sample questions
5 of 27 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "(" + x + "," + y + ")"; } } System.out.println(new Point(3, 4));What is printed?
- Acheck_circle
(3,4)
- B
Point@<hash>
- C
3,4
- D
Compile-time error
Why
<code>println(Object)</code> calls <code>toString()</code>. The override returns "(3,4)".
- A
Sample 2difficulty 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
- Dcheck_circle
(3,4)
Why
System.out.print on an object calls toString(). The overridden toString returns "(3,4)".
- A
Sample 3difficulty 2/5
public abstract class Shape { public abstract double area(); } public class Circle extends Shape { private double r; public Circle(double radius) { r = radius; } // no area method defined }What is the result of compiling Circle?
- A
Compiles fine; area() returns 0
- B
Compiles but throws RuntimeException
- Ccheck_circle
Compile error: Circle must implement area() or be declared abstract
- D
Compiles only with a warning
Why
A non-abstract subclass of an abstract class must implement all inherited abstract methods. Circle does not implement area(), so it must either implement it or be declared abstract.
- A
Sample 4difficulty 3/5
public class Shape { public double area() { return 0.0; } public String describe() { return "Area=" + area(); } } public class Square extends Shape { public double area() { return 25.0; } } Shape s = new Square(); System.out.println(s.describe());What is printed?
- A
Area=0.0
- Bcheck_circle
Area=25.0
- C
Compile-time error
- D
Area=
Why
<code>describe()</code> calls <code>area()</code>. Through dynamic dispatch, <code>Square.area()</code> is invoked, returning 25.0.
- A
Sample 5difficulty 3/5
public class Point { private int x, y; public Point(int a, int b) { x = a; y = b; } // no equals override } // Usage: Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.print(a.equals(b));What is printed?
- A
0
- B
true
- C
Compile error
- Dcheck_circle
false
Why
Without overriding equals, the inherited Object.equals compares references. a and b are different objects, so equals returns false.
- A