ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Base {
public String describe() { return "Base"; }
}
interface Describable {
String describe();
}
class Sub extends Base implements Describable {
}
public class Main {
public static void main(String[] args) {
Describable d = new Sub();
System.out.println(d.describe());
}
}- A. Compile-time error: Sub must explicitly implement describe()
- B. Base
- C. Compile-time error: describe() is ambiguous between Base and Describable
- D. null
Correct answer: B. Base
An inherited concrete method can satisfy an interface's abstract method requirement automatically, as long as the signatures (and return type) match, without Sub needing to redeclare it. Sub inherits Base.describe() and that satisfies Describable, so d.describe() returns "Base".
More OOP with C++ and Java questions
- What is printed? java class Resource { String name; Resource(String n) { name = n; System.out.print("open:" + n + " "); } void use() {…
- What is printed? cpp class Base { public: Base() { cout << "Base() "; } Base(int x) : Base() { cout << "Base(int) "; } }; int main() {…
- What is printed? java class Counter { int value; Counter(int v) { value = v; } Counter increment() { return new Counter(value + 1); }…
- What is printed? cpp struct Animal { virtual ~Animal() {} virtual void speak() const { cout << "..."; } }; struct Dog : Animal { void…
- What is printed? java class A { A() { System.out.print(id() + " "); } int id() { return 0; } } class B extends A { int val; B(int v) { val…
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…