ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class Animal { String speak() { return "animal"; } }
class Dog extends Animal { String speak() { return "dog"; } }
// static methods of the main class:
static String m(Animal a) { return "A"; }
static String m(Dog d) { return "D"; }
// in main:
Animal a = new Dog();
System.out.print(m(a) + "-" + a.speak());- A. D-dog
- B. A-animal
- C. D-animal
- D. A-dog
Correct answer: D. A-dog
Overload choice uses the compile-time type of the argument, Animal, so m(Animal) runs: A. The overridden speak is chosen at run time from the real object, a Dog: dog.
More OOP with C++ and Java questions
- What is printed? java class P { int id; P(int id) { this.id = id; } @Override public boolean equals(Object o) { return o instanceof P &&…
- What is printed? java System.out.print(5.0 / 0 + " "); System.out.print(0.0 / 0 + " "); try { System.out.print(5 / 0); } catch…
- What is printed? cpp struct R { int v = 0; R& inc() { v++; return this; } }; struct V { int v = 0; V inc() { v++; return this; } }; int…
- What is printed? cpp int a = 5; int &r = a; r = 10; int b = 20; r = b; b = 30; cout << a << " " << r;
- What is printed? java class R implements AutoCloseable { String n; R(String n) { this.n = n; System.out.print("o" + n + " "); } public…
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…