ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
protected String name() { return "Base"; }
public String greet() { return "Hi " + name(); }
}
class Child extends Base {
protected String name() { return "Child"; }
}
// in main:
Base b = new Child();
System.out.println(b.greet());- A. Hi Base
- B. Hi Child
- C. Compile-time error: greet() cannot call a protected method of another class
- D. Hi null
Correct answer: B. Hi Child
greet() is inherited unchanged by Child, but the call to name() inside it is dynamically dispatched: since b's runtime type is Child, Child.name() runs, returning "Child", so greet() prints "Hi Child". This is the template-method pattern relying on polymorphism.
More OOP with C++ and Java questions
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { virtual void f() { cout << "B"; } }; struct C : B {…
- What is printed? java interface Flyer { default String move() { return "fly"; } } interface Swimmer { default String move() { return…
- What is printed? java class Counter { protected int count = 0; void inc() { count++; } } class LoggingCounter extends Counter { @Override…
- What is printed? cpp struct Base { virtual void f() const { cout << "Base-const"; } }; struct Derived : Base { void f() const override {…
- What is printed? java class Shape { double area() { return 0; } } class Circle extends Shape { double radius; Circle(double r) { radius =…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } @Override public String toString() { return "N(" + val +…