ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
interface Shape {
    double area();
    default String describe() { return "Shape with area " + area(); }
}
class Square implements Shape {
    double side;
    Square(double s) { side = s; }
    public double area() { return side * side; }
}
// in main:
Shape s = new Square(4);
System.out.println(s.describe());
  1. A. Shape with area 4.0
  2. B. Shape with area 16.0
  3. C. Compilation error: describe() calls an abstract method
  4. D. null

Correct answer: B. Shape with area 16.0

An interface default method can freely call the interface's own abstract methods; at run time, that call (area()) dispatches virtually to the implementing class's method, Square.area() = 4*4 = 16.0, so describe() returns "Shape with area 16.0".

More OOP with C++ and Java questions

Exams that ask this topic