建設網(wǎng)站公司 優(yōu)幫云網(wǎng)站排名優(yōu)化專業(yè)定制
Java里的static import使用小結
?換了工作要把Java重新?lián)炱饋砹?#xff0c;這個在大學里用過的語言,雖然不復雜,還是有一些奇怪的地方的。比如static Slgluimport。
Static import是JDK 1.5中引進的特性,不過讀大學那會還真沒注意到。它的作用是把靜態(tài)(static)的方法或者常量import進來。比如:
import static java.lang.Math.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("Considering a circle with a diameter of 5 cm, it has:");
System.out.println("A circumference of " + (Math.PI * 5) + " cm");
System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + " sq. cm");
}
}
使用了static import之后,就可以寫成:
import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
public static void main(String[] args) {
out.println("Hello World!");
out.println("Considering a circle with a diameter of 5 cm, it has:");
out.println("A circumference of " + (PI * 5) + " cm");
out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
}
}
注意”Math.”和”System.”可以省略掉了。
Static import和import的規(guī)則類似,引用的內(nèi)容不可以有歧義。
Slglu
使用了static import,代碼會變短,增加了可讀性,但一定程度上會對代碼整體的理解造成困難,因為常量和靜態(tài)方法看上去像全局變得和全局方法了,有點C++的味道,失去了一些OO的美感。