Java 'static‘关键字的几种用法

2025-10-30 05:24:44

1、static变量:

1.类级别的。

2.常与final一起使用定义常量。

3.非线程安全的。

Java 'static‘关键字的几种用法

2、类中的static方法:

如图所示,这是Collections中的一个static方法。

类中的static方法一般多用于帮助类或者util类中。

Java 'static‘关键字的几种用法

3、接口中的static方法:

1从Java8开始,接口中也可以有default和static方法了。

2接口中的static方法不允许实现类去实现这个方法,否则会编译错误。

Java 'static‘关键字的几种用法

4、static块:

1.它只能访问static变量和static方法。

2.当类一加载,static块中的内容就会加载了。

3.一般用于初始化某些必须的内容。

Java 'static‘关键字的几种用法

5、static类:

1.它只能是内部类,不能是一级类。

如String类中的CaseInsensitiveComparator就是一个static类

Java 'static‘关键字的几种用法

6、import static用法

1.将static方法和常量引用,

如import static com.test.A.DEFAULT;

这时的DEFAULT是个常量名.

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.assertFalse;

这里的assertEquals,assertFalse是static方法。

2.如果多次使用某个类下的常量和static方法,可以使用这种方法:

import static org.junit.Assert.*;

比如我们常用的测试类,就可以这样引用。

Java 'static‘关键字的几种用法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢