static import java_Java里的static import使用小结

换了工作要把Java重新捡起来了,这个在大学里用过的语言,虽然不复杂,还是有一些奇怪的地方的。比如static import。

Static import是JDK 1.5中引进的特性,不过读大学那会还真没注意到。它的作用是把静态(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的规则类似,引用的内容不可以有歧义。

使用了static import,代码会变短,增加了可读性,但一定程度上会对代码整体的理解造成困难,因为常量和静态方法看上去像全局变得和全局方法了,有点C++的味道,失去了一些OO的美感。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值