更新時間:2022-09-27 10:28:15 來源:動力節(jié)點(diǎn) 瀏覽1563次
以下是類(靜態(tài))和實(shí)例變量之間的顯著差異。
| 實(shí)例變量 | 靜態(tài)(類)變量 |
|---|---|
| 實(shí)例變量在類中聲明,但在方法、構(gòu)造函數(shù)或任何塊之外。 | 類變量也稱為靜態(tài)變量,在類中使用 static 關(guān)鍵字聲明,但在方法、構(gòu)造函數(shù)或塊之外。 |
| 實(shí)例變量在使用關(guān)鍵字“new”創(chuàng)建對象時創(chuàng)建,并在對象被銷毀時銷毀。 | 靜態(tài)變量在程序啟動時創(chuàng)建,在程序停止時銷毀。 |
| 實(shí)例變量可以通過調(diào)用類內(nèi)部的變量名直接訪問。但是,在靜態(tài)方法中(當(dāng)實(shí)例變量具有可訪問性時),應(yīng)該使用完全限定名稱來調(diào)用它們。ObjectReference.VariableName。 | 靜態(tài)變量可以通過調(diào)用類名ClassName.VariableName來訪問。 |
| 實(shí)例變量保存的值必須由多個方法、構(gòu)造函數(shù)或塊引用,或者必須在整個類中存在的對象狀態(tài)的基本部分引用。 | 每個類只有一個類變量的副本,無論從中創(chuàng)建了多少對象。 |
例子
public class VariableExample{
int myVariable;
static int data = 30;
public static void main(String args[]){
VariableExample obj = new VariableExample();
System.out.println("Value of instance variable: "+obj.myVariable);
System.out.println("Value of static variable: "+VariableExample.data);
}
}
輸出
Value of instance variable: 0
Value of static variable: 30
相關(guān)閱讀

初級 202925

初級 203221

初級 202629

初級 203743