ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class Base {
void greet(Object o) { System.out.print("Object "); }
}
class Derived extends Base {
void greet(String s) { System.out.print("String "); } // overload, not override
}
// in main:
Derived d = new Derived();
Base b = d;
b.greet("hi");
d.greet("hi");- A. String String
- B. Object String
- C. Object Object
- D. String Object
Correct answer: B. Object String
greet(String) in Derived is a NEW OVERLOAD (different parameter type), not an override of greet(Object); overload resolution happens at compile time based on the STATIC type of the reference. b's static type is Base, which only has greet(Object), so b.greet("hi") calls that, printing "Object". d's static type is Derived, which offers both overloads and picks the more specific greet(String), printing "String".
More OOP with C++ and Java questions
- What is printed? java class Base { static void show() { System.out.print("Base.static "); } } class Derived extends Base { static void…
- 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…