ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Animal {
void speak() { System.out.print(".."); }
}
class Dog extends Animal {
void speak() { System.out.print("Woof"); }
}
class Puppy extends Dog {
void speak() { System.out.print("Yip"); }
}
// in main:
Animal a = new Puppy();
a.speak();- A. ..
- B. Woof
- C. Yip
- D. Compile-time error: Animal has no speak() that matches Puppy
Correct answer: C. Yip
Method calls in Java are dispatched using the object's actual runtime class, regardless of the reference's declared type. a holds a Puppy, and Puppy overrides speak() again (overriding Dog's override), so the most-derived version, Yip, runs.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { public: virtual ~Base() { cout << "~Base "; } }; struct Derived : Base { int data = new int[10]…
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…
- What is printed? java abstract class Shape { abstract double area(); String describe() { return "Area=" + area(); } } class Square extends…
- What is printed? java class Base { protected String name() { return "Base"; } public String greet() { return "Hi " + name(); } } class…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { virtual void f() { cout << "B"; } }; struct C : B {…
- What is printed? java interface Flyer { default String move() { return "fly"; } } interface Swimmer { default String move() { return…