在 Java 中使用静态导入以调用 Math 类的 sqrt() 和 pow() 方法
静态导入意味着如果将类的字段和方法定义为公有静态,则可以在代码中使用这些字段和方法,而无需指定它们的类。
包 java.lang 中的 Math 类方法 sqrt() 和 pow() 已被静态导入。一个展示这一点的程序如下所示
示例
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
public class Demo {
public static void main(String args[]) {
double num = 4.0;
System.out.println("The number is: " + num);
System.out.println("The square root of the above number is: " + sqrt(num));
System.out.println("The square of the above number is: " + pow(num, 2));
}
}输出
The number is: 4.0 The square root of the above number is: 2.0 The square of the above number is: 16.0
现在,让我们了解一下上面的程序。
由于 java.lang 包使用了静态导入,因此不必使用 Math 类和方法 sqrt() 以及 pow()。它会显示 num 及其平方根和平方。一个演示此过程的代码片段如下所示
double num = 4.0;
System.out.println("The number is: " + num);
System.out.println("The square root of the above number is: " + sqrt(num));
System.out.println("The square of the above number is: " + pow(num, 2));
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP