ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
Base() { System.out.print("Base "); }
protected Base(int x) { System.out.print("Base(int) "); }
}
class Sub extends Base {
Sub() { super(5); System.out.print("Sub "); }
}
class Grand extends Sub {
Grand() { System.out.print("Grand "); }
}
public class Main {
public static void main(String[] args) { new Grand(); }
}- A. Base Sub Grand
- B. Base(int) Sub Grand
- C. Grand Sub Base(int)
- D. Compile-time error: Grand cannot call a protected constructor of Base indirectly
Correct answer: B. Base(int) Sub Grand
Grand()'s implicit super() call goes to Sub(), which explicitly calls super(5), reaching Base(int) (protected is fine since Sub is a subclass), printing Base(int). Sub()'s own body then prints Sub, and finally Grand()'s body prints Grand. Base's no-arg constructor is never invoked at all.
More OOP with C++ and Java questions
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle-start "); } } class ElectricCar extends Vehicle { @Override…
- What is printed? cpp struct Base { Base() { cout << "Base "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1 "; } }; struct Mixin2 {…
- What is printed? java class Base { public String describe() { return "Base"; } } interface Describable { String describe(); } class Sub…
- What is printed? java class Resource { String name; Resource(String n) { name = n; System.out.print("open:" + n + " "); } void use() {…
- What is printed? cpp class Base { public: Base() { cout << "Base() "; } Base(int x) : Base() { cout << "Base(int) "; } }; int main() {…
- What is printed? java class Counter { int value; Counter(int v) { value = v; } Counter increment() { return new Counter(value + 1); }…