java 导入 Math.PI 作为参考或值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28770927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing Math.PI as reference or value
提问by user4702831
I'm preparing for a basic certification in Java.
我正在准备 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;
我回答 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.
语句 import java.lang.Math;并导入 java.lang.Math.*;不会使代码能够编译和运行。这些导入语句将只允许 Math.PI 作为对 PI 常量的引用。
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?
我的问题是:只允许引用 PI 常量的导入语句有什么问题?该值是否会未初始化且为零?
回答by Sotirios Delimanolis
This
这
import java.lang.Math.*;
imports all (accessible) types declared within Math
.
导入在Math
.
This
这
import java.lang.Math;
is redundant because Math
is part of java.lang
which is imported by default.
是多余的,因为Math
它的一部分java.lang
是默认导入的。
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.
导入static
成员,Math.PI
以便您可以在源代码中使用其简单名称。
回答by Clashsoft
'Allow Math.PI as a reference to the PI constant' means that your code will have to look like this in order to work:
“允许 Math.PI 作为对 PI 常量的引用”意味着您的代码必须如下所示才能工作:
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.
什么import java.lang.Math;
是导入类,java.lang.Math
以便您可以使用Math
而不是限定版本来引用它java.lang.Math
。import java.lang.Math.*;
对Math
所有嵌套类执行相同的操作,但不是它的成员。