ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
void show() { System.out.print("Base"); }
}
class Sub extends Base {
void show() { System.out.print("Sub"); }
void show(String s) { System.out.print("Sub:" + s); }
}
public class Main {
public static void main(String[] args) {
Base b = new Sub();
b.show();
}
}- A. Base
- B. Sub
- C. Compile-time error: show() is ambiguous since Sub overloads it too
- D. Sub:null
Correct answer: B. Sub
Sub.show() with no arguments has the identical signature to Base.show(), so it truly overrides it (the extra overload show(String) is a separate, additional method). b.show() with no arguments dispatches dynamically to the real object's class, Sub, printing Sub.
More OOP with C++ and Java questions
- What is printed? cpp struct Animal { virtual std::string sound() const = 0; void makeSound() const { cout << sound(); } virtual ~Animal()…
- What is printed? java class Base { Base() { System.out.print("Base-ctor "); } static { System.out.print("Base-static "); } } class Sub…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct Mid : Base { }; struct Leaf : Mid { void f() override {…
- What is printed? java public class Main { static class Base { public String toString() { return "Base"; } public boolean equals(Object o)…
- What is printed? cpp template <typename T> T maxVal(T a, T b) { return a > b ? a : b; } int main() { cout << maxVal(3, 7) << " " <<…
- What happens? java interface A { default String id() { return "A"; } } interface B { default String id() { return "B"; } } class D…