OCP Stage 2 Problem 1.17 – Explanation

Given the class:

public class Archimedes {
    public static double getCircleArea(double radius) {
        return PI * pow(radius, 10);    // raises the 1st argument to the power of the 2nd argument
}
    public static double getSquareArea(double side) {
        return pow(side, 10);
    }
}

Which import declaration(s) must appear before the class declaration for Archimedes to compile?

A. import java.lang.*;
B. import java.lang.Math;
import java.lang.Math.PI;
import java.lang.Math.pow;
C. static import java.lang.Math;
D. import static java.lang.Math.*;

 

The correct answer is D.

 

The import declaration in Java does not actually import anything: it’s a just a convenient way to tell the compiler that it needs to look into such and such package for such and such public datatype(s). Should the datatype lack the public modifier, this particular class or enum becomes inaccessible from outside its package.

 

Reminders:

  • interfaces’ visibility is public by default;
  • while enums themselves do not have default visibility, their constants are implicitly public static final, just like the constants in interfaces;
  • when importing a static method, we do not specify parens:
import static java.lang.Math.pow;
import static java.lang.Math.pow();     // INVALID

 

Option A is out because it addresses wrong package; more than that, java.lang is available to the compiler by default.

Option B fails compilation because the regular import does not support access to static members, which makes these two stats illegal:

import java.lang.Math.PI;
import java.lang.Math.pow;

Option C uses incorrect syntax: it should’ve been static import statement.

 

Takeaway:

Although we routinely mention static imports, in code we always must use import static (resembling a command we give to the compiler).

 

Objective:
Java Class Design

Sub-Objective:
Implement encapsulation

Leave Comment

Your email address will not be published.