ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Shape {
double area() { return 0.0; }
}
class Rectangle extends Shape {
double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
@Override
double area() { return w * h; }
}
class Square extends Rectangle {
Square(double s) { super(s, s); }
}
public class Main {
public static void main(String[] args) {
Shape s = new Square(4);
System.out.println(s.area());
}
}- A. 0.0
- B. 4.0
- C. 16.0
- D. Compile-time error: Square must override area() itself
Correct answer: C. 16.0
Square does not override area(); it simply inherits Rectangle's implementation, which uses w and h set via super(s, s), both 4. Dynamic dispatch on s (actually a Square) finds the nearest implementation up the chain, Rectangle.area(), returning 4*4 = 16.0.
More OOP with C++ and Java questions
- What is printed? java class Vehicle implements Comparable<Vehicle> { int speed; Vehicle(int s) { speed = s; } public int compareTo(Vehicle…
- What is printed? cpp struct Base { virtual Base& self() { cout << "Base::self "; return this; } }; struct Derived : Base { Derived& self()…
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…
- What happens when this is compiled? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int…
- What is printed? cpp struct Logger { Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger() { cout << "Ctor…
- What is printed? java class Base { Base() { System.out.print("Base "); } } abstract class Middle extends Base { Middle() {…