Java里的static import使用小结
换了工作要把Java重新捡起来了,这个在大学里用过的语言,虽然不复杂,还是有一些奇怪的地方的。比如staticimport。
Staticimport是JDK1.5中引进的特性,不过读大学那会还真没注意到。它的作用是把静态(static)的方法或者常量import进来。比如:
importstaticjava.lang.Math.*;
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("HelloWorld!");
System.out.println("Consideringacirclewithadiameterof5cm,ithas:");
System.out.println("Acircumferenceof"+(Math.PI*5)+"cm");
System.out.println("Andanareaof"+(Math.PI*Math.pow(2.5,2))+"sq.cm");
}
}
使用了staticimport之后,就可以写成:
importstaticjava.lang.Math.*;
importstaticjava.lang.System.out;
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
out.println("HelloWorld!");
out.println("Consideringacirclewithadiameterof5cm,ithas:");
out.println("Acircumferenceof"+(PI*5)+"cm");
out.println("Andanareaof"+(PI*pow(2.5,2))+"sq.cm");
}
}
注意”Math.”和”System.”可以省略掉了。
Staticimport和import的规则类似,引用的内容不可以有歧义。
使用了staticimport,代码会变短,增加了可读性,但一定程度上会对代码整体的理解造成困难,因为常量和静态方法看上去像全局变得和全局方法了,有点C++的味道,失去了一些OO的美感。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短