在 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));
廣告