ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Base {
public static void greet() { System.out.print("Base.greet "); }
}
class Sub extends Base {
public static void greet() { System.out.print("Sub.greet "); }
}
public class Main {
static void show(Base b) {
b.greet();
}
public static void main(String[] args) {
show(new Sub());
}
}- A. Sub.greet
- B. Base.greet
- C. Compile-time error: cannot call a static method via an instance reference inside show()
- D. Both print, Base.greet then Sub.greet
Correct answer: B. Base.greet
b.greet() is still a static method call under the hood, resolved purely by the declared/parameter type of b, which is Base, regardless of what object is actually passed in. It always prints Base.greet, never Sub.greet, no matter what concrete subtype is passed to show().
More OOP with C++ and Java questions
- What is printed? cpp struct Base { void greet() { cout << "Base::greet "; } }; struct Sub : Base { void greet() { cout << "Sub::greet "; }…
- What is printed? cpp struct Base { static void hello() { cout << "Base::hello "; } }; struct Derived : Base { static void hello() { cout…
- What is printed? java class Outer { static int x = 100; static class Nested { int x = 200; void show() { System.out.println(x + " " +…
- What is printed? cpp class Singleton { static Singleton instance; Singleton() { cout << "Created "; } public: static Singleton get() { if…
- What is printed? cpp struct Base { int level = 1; }; struct Mid : Base { int level = 2; }; struct Leaf : Mid { int level = 3; void show()…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…