ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Employee {
double bonus() { return 1000; }
double pay() { return 50000 + bonus(); }
}
class Manager extends Employee {
@Override
double bonus() { return 5000; }
}
// in main:
Employee e = new Manager();
System.out.println(e.pay());- A. 51000.0
- B. 55000.0
- C. Compile-time error: pay() cannot see Manager's bonus()
- D. 50000.0
Correct answer: B. 55000.0
pay() is inherited by Manager unchanged, but its call to bonus() is dynamically dispatched against the real object. Since e is actually a Manager, bonus() returns 5000, making pay() return 50000 + 5000 = 55000.0.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { Base() { cout << "CtorBase "; } virtual ~Base() { cout << "DtorBase "; } }; struct Derived : Base {…
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…