ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
static void show() { System.out.print("Base.static "); }
}
class Derived extends Base {
static void show() { System.out.print("Derived.static "); } // hides, doesn't override
}
// in main:
Base b = new Derived();
b.show();- A. Derived.static
- B. Compilation error: static methods cannot be called via instance reference
- C. Compilation error: duplicate show()
- D. Base.static
Correct answer: D. Base.static
Static methods are resolved by the reference's STATIC/compile-time type, never by the object's runtime type (they are not polymorphic). b's declared type is Base, so b.show() resolves to Base.show() at compile time, printing "Base.static", even though b actually refers to a Derived object at runtime.
More OOP with C++ and Java questions
- What is printed? java class Base { protected int code = 1; } class Derived extends Base { int code = 2; } // in main: Base b = new…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle starts "); } } interface Electric { default void start() {…
- What is printed? java interface Counter { int next(); private int helper() { return 100; } default int nextPlusHelper() { return next() +…
- What is printed? cpp class Account { double balance = 0; friend void deposit(Account& a, double amt); public: double getBalance() const {…
- What is printed? java abstract class Shape { abstract double area(); } interface Colorable { String color(); } class Circle extends Shape…
- What is printed? java class Base implements Cloneable { int x = 5; @Override public Base clone() throws CloneNotSupportedException {…