ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
abstract class Shape {
    abstract double area();
    String describe() { return "Area=" + area(); }
}
class Square extends Shape {
    double side;
    Square(double s) { side = s; }
    double area() { return side * side; }
}
// in main:
Shape s = new Square(4);
System.out.println(s.describe());
  1. A. Compile-time error: Shape cannot call an abstract method from describe()
  2. B. Area=0.0
  3. C. Area=16.0
  4. D. Compile-time error: Shape cannot be used as a reference type since it is abstract

Correct answer: C. Area=16.0

describe() is a concrete method in the abstract class and may freely call the abstract method area(); it is resolved dynamically against the actual object, a Square, whose area() returns 4*4 = 16.0. A reference variable of an abstract type is completely legal, only instantiation of the abstract type itself is forbidden.

More OOP with C++ and Java questions

Exams that ask this topic