ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
interface Shape {
    static double unit() { return 1.0; }
    double area();
}
class Square implements Shape {
    double side;
    Square(double s) { side = s; }
    public double area() { return side * side; }
}
public class Main {
    public static void main(String[] args) {
        Square sq = new Square(3);
        System.out.println(Shape.unit() + " " + sq.area());
    }
}
  1. A. 1.0 9.0
  2. B. Compile-time error: interfaces cannot have static methods
  3. C. 1.0 1.0
  4. D. Compile-time error: sq.unit() must be used instead of Shape.unit()

Correct answer: A. 1.0 9.0

Since Java 8, interfaces may declare static methods, but they belong to the interface itself and must be called as Interface.method(), never inherited or called through an implementing instance. Shape.unit() returns 1.0, and sq.area() (an abstract method Square implements) returns 3*3 = 9.0.

More OOP with C++ and Java questions

Exams that ask this topic