1 靜態(tài)變量
- 靜態(tài)變量:又稱為類變量谷异,也就是說這個變量屬于類的,類所有的實例都共享靜態(tài)變量攻礼,可以直接通過類名來訪問它胖齐。靜態(tài)變量在內(nèi)存中只存在一份玻淑。
- 實例變量:每創(chuàng)建一個實例就會產(chǎn)生一個實例變量,它與該實例同生共死呀伙。
public class A {
private int x; // 實例變量
private static int y; // 靜態(tài)變量
public static void main(String[] args) {
// int x = A.x; // Non-static field 'x' cannot be referenced from a static context
A a = new A();
int x = a.x;
int y = A.y;
}
}
2 靜態(tài)方法
靜態(tài)方法在類加載的時候就存在了补履,它不依賴于任何實例。所以靜態(tài)方法必須有實現(xiàn)剿另,也就是說它不能是抽象方法箫锤。
public abstract class A {
public static void func1(){
}
// public abstract static void func2(); // Illegal combination of modifiers: 'abstract' and 'static'
}
只能訪問所屬類的靜態(tài)字段和靜態(tài)方法贬蛙,方法中不能有 this 和 super 關(guān)鍵字。
public class A {
private static int x;
private int y;
public static void func1(){
int a = x;
// int b = y; // Non-static field 'y' cannot be referenced from a static context
// int b = this.y; // 'A.this' cannot be referenced from a static context
}
}
3 靜態(tài)語句塊
靜態(tài)語句塊在類初始化時運行一次谚攒。
public class A {
static {
System.out.println("123");
}
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
}
}
4 靜態(tài)內(nèi)部類
非靜態(tài)內(nèi)部類依賴于外部類的實例阳准,而靜態(tài)內(nèi)部類不需要。
public class OuterClass {
class InnerClass {
}
static class StaticInnerClass {
}
public static void main(String[] args) {
// InnerClass innerClass = new InnerClass(); // 'OuterClass.this' cannot be referenced from a static context
OuterClass outerClass = new OuterClass();
InnerClass innerClass = outerClass.new InnerClass();
StaticInnerClass staticInnerClass = new StaticInnerClass();
}
}
靜態(tài)內(nèi)部類不能訪問外部類的非靜態(tài)的變量和方法馏臭。
5 靜態(tài)導包
在使用靜態(tài)變量和方法時不用再指明 ClassName野蝇,從而簡化代碼,但可讀性大大降低括儒。
import static com.xxx.ClassName.*
6 初始化順序
靜態(tài)變量和靜態(tài)語句塊優(yōu)先于實例變量和普通語句塊绕沈,靜態(tài)變量和靜態(tài)語句塊的初始化順序取決于它們在代碼中的順序。
public static String staticField = "靜態(tài)變量";
static {
System.out.println("靜態(tài)語句塊");
}
public String field = "實例變量";
{
System.out.println("普通語句塊");
}
最后才是構(gòu)造函數(shù)的初始化塑崖。
public InitialOrderTest() {
System.out.println("構(gòu)造函數(shù)");
}
存在繼承的情況下,初始化順序為:
- 父類(靜態(tài)變量痛倚、靜態(tài)語句塊)
- 子類(靜態(tài)變量规婆、靜態(tài)語句塊)
- 父類(實例變量、普通語句塊)
- 父類(構(gòu)造函數(shù))
- 子類(實例變量蝉稳、普通語句塊)
- 子類(構(gòu)造函數(shù))