在java中, static是常用关键字,主要用途归结如下:
1:修饰类成员变量:用static修饰的静态变量是类变量,类实例共享类变量。主要用于定义常量、单例。
public class StaticKeyWord {
/* 定义常量 */
private final static String STATIC_KEY_WORD = "static_key_word";
}
2:修饰类方法:静态方法是类方法,类实例共享。
public class StaticKeyWord {
/* 定义常量 */
private final static String STATIC_KEY_WORD = "static_key_word";
/* 修饰静态方法 */
public static String getStaticKeyWord(){
return StaticKeyWord.STATIC_KEY_WORD;
}
}
3:静态代码块:常用语对静态变量赋值,类初始化时代码顺序加载,main方法的执行结果为“Hi, block1”。
public class StaticKeyWord {
/* 定义常量 */
private final static String STATIC_KEY_WORD = "static_key_word";
private static String blockString;
/* 修饰静态方法 */
public static String getStaticKeyWord(){
return StaticKeyWord.STATIC_KEY_WORD;
}
/* 静态代码块 1 */
static{
blockString = "Hi, block";
}
public static void setBlockString(){
blockString = "Hi, block1";
}
/* 静态代码块 2 */
static{
blockString = "Hi, block2";
}
public static void main(String[] args) {
setBlockString();
System.out.println(blockString);
}
}
运行main函数结果
Hi, block1
Process finished with exit code 0
4:静态导包: 直接使用静态类中成员变量和方法。
package com.booby.blog.micro;
public class MicroStatic {
public static String MICRO_STATIC_IMPORT = "micro_static";
public static String staticImport(){
return "micro_static_method";
}
}
package com.booby.blog.service.impl;
import static com.booby.blog.micro.MicroStatic.MICRO_STATIC_IMPORT;
import static com.booby.blog.micro.MicroStatic.staticImport;
public class StaticKeyWord {
public static void main(String[] args) {
System.out.println(MICRO_STATIC_IMPORT);
System.out.println(staticImport());
}
}
5:静态类:静态类一定是静态内部类,具体使用稍后整理。
public class StaticKeyWord {
public static void main(String[] args) {
StaticKeyWord.Inner inner = new StaticKeyWord.Inner();
System.out.println(inner.innerMethod());
System.out.println(StaticKeyWord.Inner.innerStaticMethod());
System.out.println(Inner.innerMember);
}
/* 内部静态类 */
static class Inner{
/* 内部类静态成员变量 */
public static String innerMember = "静态成员变量";
/* 内部类静态方法 */
public static String innerStaticMethod(){
return "inner static method";
}
/* 内部类实例方法 */
public String innerMethod(){
return "inner method";
}
}
}