關鍵字static
- 靜態成員屬於類本身的,而不是屬於對象,被類的所有對象所共有
- 即使不創建對象,也可以使用類本身的靜態成員
- 靜態成員分爲
- 靜態數據成員
- 靜態方法成員
- 使用靜態成員的兩種方法
- 類名.靜態成員名
- 類對象名.靜態成員名
- 編寫使用靜態變量統計一個類產生的實例對象的個數的程序
//程序證明static屬性i屬於類本身,創建對象的時候不再單獨創建數據成員i的內存
class A
{
public static int i = 10;
public void show()
{
System.out.printf("%d\n",i);
}
}
class Teststatic_1
{
public static void main(String[] args)
{
A aa1 = new A();
A aa2 = new A();
A aa3 = new A();
aa1.i = 20;
aa2.show();
System.out.printf("%d\n",aa3.i);
}
}
程序運行示例:
——————————————————————————————
20
20
——————————————————————————————
//static屬性i是屬於類本身,或者講:沒有對象,我們仍然可以直接通過類名的方式訪問該類內部的static屬性
//static方法 同理
class A{
public static int i = 10;
public static void f()
{
System.out.printf("%d\n",A.i);
}
}
class Teststatic_2
{
public static void main(String[] args)
{
System.out.printf("%d\n",A.i);
A.f();
}
}
程序運行示例:
——————————————————————————————
10
10
——————————————————————————————
//static屬性和方法雖然屬於類本身,雖然可以通過類名的方式訪問
//但是static屬性和方法很明顯也屬於類對象,當然也可以類對象名的方式進行訪問
class A{
public static int i = 10;
public static void f()
{
System.out.printf("%d\n",A.i);
}
}
class Teststatic_3
{
public static void main(String[] args)
{
// System.out.printf("%d\n",A.i);
// A.f();
A aa = new A();
aa.f();
System.out.printf("%d\n",aa.i);
}
}
程序運行示例:
——————————————————————————————
10
10
——————————————————————————————
//只有非private的static成員纔可以通過類名的方式訪問
//static只是表明了該成員具有了可以通過類名訪問的潛在特徵
//但是否可以通過類名訪問,還必須滿足一個條件,該成員必須是非private
class A{
public static int i = 10;
private static void f()
{
System.out.printf("%d\n",A.i);
}
}
class Teststatic_4
{
public static void main(String[] args)
{
// System.out.printf("%d\n",A.i); OK
A.f();
// A aa = new A();
// aa.f(); OK
// System.out.printf("%d\n",aa.i); OK
}
}
程序運行示例:
——————————————————————————————
Teststatic_4.java:18: 錯誤: f() 在 A 中是 private 訪問控制
A.f();
^
1 個錯誤
______________________________
//說明靜態方法不能訪問非靜態成員
//說明非靜態方法可以訪問靜態成員
class A{
private static int i = 10;
public int j = 99;
public static void f()
{
//g(); //error 靜態方法不能訪問非靜態成員
// j = 22; //error 靜態方法不能訪問非靜態成員
System.out.printf("FFFF\n");
}
public void g()
{
f(); //OK 說明非靜態方法可以訪問靜態成員
System.out.printf("GGGG\n");
System.out.printf("%d\n",i);
}
}
class Teststatic_5
{
public static void main(String[] args)
{
A aa = new A();
aa.g();
// System.out.printf("%d\n",aa.i); OK
}
}
程序運行示例:
——————————————————————————————
FFFF
GGGG
10
______________________________
class A
{
public int i;
private static int cnt = 0;
public A()
{
cnt++;
}
public A(int i)
{
this.i = i;
cnt++; //this.cnt -->error 靜態屬於類,故沒有this指針
}
public static int getCnt()
{
return cnt;
}
}
class M
{
public static void main(String[] args)
{
A aa1 = new A();
A aa2 = new A();
System.out.printf("%d\n",A.getCnt());
}
}
程序運行示例:
——————————————————————————————
2
______________________________
-
在靜態方法裏只能直接調用同類中其他的靜態成員(包括變量和方法),而不能直接訪問類中的非靜態成員。這是因爲,對於非靜態的方法和變量,需要先創建類的實例對象後纔可使用,而靜態方法在使用前不用創建任何對象
-
靜態方法不能以任何方式應用this和super關鍵字(super關鍵字在下一章講解)。與上面的道理一樣,因爲靜態方法在引用的對象根本就沒有產生。
-
靜態方法只能訪問類的靜態成員。
但非靜態方法卻可以訪問類中所有成員,包括靜態成員