ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Shape {
    void draw() { System.out.println("Shape.draw"); }
}
class Circle extends Shape {
    void draw() { System.out.println("Circle.draw"); }
    void draw(int radius) { System.out.println("Circle.draw(" + radius + ")"); }
}
// in main:
Shape s = new Circle();
// s.draw(5); // line X
What happens if line X is uncommented?
  1. A. It compiles and prints Circle.draw(5)
  2. B. Compilation error: draw(int) is not a member of Shape (overloads in a subclass aren't visible through a base-typed reference)
  3. C. It compiles and prints Shape.draw
  4. D. It throws NoSuchMethodError at run time

Correct answer: B. Compilation error: draw(int) is not a member of Shape (overloads in a subclass aren't visible through a base-typed reference)

Overload resolution only searches the methods declared/inherited in the STATIC type Shape, which has no draw(int) at all (it's a Circle-only addition), so the compiler rejects s.draw(5) outright — you would need to declare s as Circle, or cast, to call that overload.

More OOP with C++ and Java questions

Exams that ask this topic