Importing Math.PI as reference or value

我是研究僧i 提交于 2019-12-19 10:08:50

问题


I'm preparing for a basic certification in Java.

I'm a little confused by the answer to a question that I have got right(!):-

Given:

 public class Circle {
     static double getCircumference(double radius ) {
          return PI * 2 * radius;
     }
     public static double getArea(double radius) {
          return PI * radius * radius;
     }
}

Which import statement will enable the code to compile and run?

import java.lang.*;

import static java.lang.Math.PI;

import java.lang.Math.*;

import java.lang.Math;

I answered import static java.lang.Math.PI;

BUT the explanation of two other options below confuses me:-

The statements import java.lang.Math; and import java.lang.Math.*; will not enable the code to compile and run. These import statements will only allow Math.PI as a reference to the PI constant.

My question is: what would be wrong with the import statements only allowing a reference to the PI constant? Would the value be uninitialized and zero?


回答1:


'Allow Math.PI as a reference to the PI constant' means that your code will have to look like this in order to work:

static double getCircumference(double radius ) {
      return Math.PI * 2 * radius;
 }
 public static double getArea(double radius) {
      return Math.PI * radius * radius;
 }

What import java.lang.Math; does is importing the class java.lang.Math so you can reference it with Math instead of the qualified version java.lang.Math. import java.lang.Math.*; does the same for Math and all nested classes, but not it's members.




回答2:


This

import java.lang.Math.*;

imports all (accessible) types declared within Math.

This

import java.lang.Math;

is redundant because Math is part of java.lang which is imported by default.

Both will require that you use

Math.PI

to access the field.

This

import static java.lang.Math.PI;

imports the static member Math.PI so that you can use its simple name in your source code.



来源:https://stackoverflow.com/questions/28770927/importing-math-pi-as-reference-or-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!