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 XWhat happens if line X is uncommented?- A. It compiles and prints Circle.draw(5)
- B. Compilation error: draw(int) is not a member of Shape (overloads in a subclass aren't visible through a base-typed reference)
- C. It compiles and prints Shape.draw
- 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
- Does this compile? java class Base { void greet() { System.out.println("Base.greet"); } } class Derived extends Base { @Override void…
- What is printed? java class Repo<T> { private List<T> items = new ArrayList<>(); void add(T item) { items.add(item); } T get(int i) {…
- What is printed? java interface Shape { double area(); default String describe() { return "Shape with area " + area(); } } class Square…
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…