ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
void greet() { System.out.print("Base "); helper(); }
private void helper() { System.out.print("BaseHelper "); }
}
class Sub extends Base {
private void helper() { System.out.print("SubHelper "); }
}
public class Main {
public static void main(String[] args) { new Sub().greet(); }
}- A. Base SubHelper
- B. SubHelper Base
- C. Base BaseHelper
- D. Compile-time error: helper() is redeclared with the same signature in Sub
Correct answer: C. Base BaseHelper
private methods are not inherited and cannot be overridden; Sub.helper() is a completely separate, unrelated method confined to Sub's own scope (declaring it is legal, not a redefinition error). Base.greet()'s internal call to helper() can only ever resolve to Base's own private helper(), printing Base BaseHelper regardless of the actual object's class.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void save() { cout << "BaseSave "; } }; struct Derived : Base { void save() override { cout <<…
- What is printed? java class Animal { String sound() { return "..."; } } class Dog extends Animal { @Override String sound() { return…
- What is printed? cpp struct Base { virtual int value() const { return 10; } }; struct Derived : Base { int value() const override { return…
- What is printed? java interface Payable { double rate(); default double monthly(double hours) { return hours rate(); } } class Intern…
- What is printed? cpp struct Base { virtual void print() const { cout << "Base"; } friend ostream& operator<<(ostream &os, const Base &b) {…
- What is printed? java class Shape { public boolean equals(Object o) { return o instanceof Shape; } public int hashCode() { return 1; } }…