成員變數(member variable)與區域變數(local variable)看起來都是變數,實際上從位置、記憶體到生命週期都不同。釐清這四點,是讀懂 Java 記憶體模型的起點。
The local variable xxx may not have been initialized。package demo;
public class VariableDemo {
String name = "成員變量";
public static void main(String[] args) {
new VariableDemo().show();
}
public void show() {
String name = "局部變量";
System.out.println(name);
}
}
輸出為 局部變量。可見取用變數時遵循就近原則:區域變數遮蔽了同名的成員變數。若要在方法內明確指向成員變數,可利用 this(代表目前物件本身):
public void show() {
String name = "局部變量";
System.out.println(this.name);
}
此時輸出變成 成員變量。這也是 setter 裡常寫 this.name = name; 的原因——不寫 this,賦值只會落在區域變數上,成員變數永遠是 null。