- 類變量:獨立于方法之外的變量,用static修飾
- 實例變量:獨立于方法之外的變量,不過沒有static修飾
- 局部變量:類的方法中的變量
示例1:
public class test_A {static int a;//類變量(靜態變量)String b;//實例變量public static void main(String[] args) {int c=0;//局部變量}void b(int e){//參數e也是局部變量int d=0;//局部變量}
}
- 實例變量存儲java對象內部,在堆內存中,在構造方法執行的時候初始化
- 靜態變量在類加載的時候初始化,不需要創建對象,內存就開辟了
- 實例變量為所屬對象所私有,而類變量為所有對象所共有
示例2:
public class test_B {static int value_s=0;int value1=1;
}
public class test_C {public static void main(String[] args) {test_B b1=new test_B();test_B b2=new test_B();b1.value_s=99;b1.value1=100;System.out.println(b2.value_s);//輸出99System.out.println(b2.value1);//輸出1b2.value_s=3;System.out.println(b1.value_s);//輸出3System.out.println(b2.value_s);//輸出3}
}