当前位置: 移动技术网 > IT编程>开发语言>Java > Java里的static import使用小结

Java里的static import使用小结

2019年07月22日  | 移动技术网IT编程  | 我要评论

换了工作要把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的美感。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网