Importing Math.PI as reference or value

前端 未结 2 1695
情歌与酒
情歌与酒 2021-01-15 14:44

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:

 publ         


        
相关标签:
2条回答
  • 2021-01-15 14:47

    '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.

    0 讨论(0)
  • 2021-01-15 14:47

    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.

    0 讨论(0)
提交回复
热议问题