1、static作用主要有兩方面:其一,當希望類中的某些屬性被所有對象共享,則就必須將其聲明為static屬性;其二,如果一個類中的方法由類名調用,則可以將其聲明為static方法。
2、需要注意的是,非static聲明的方法可以去調用statci聲明的屬性和方法;但是static聲明的方法不能調用非static類型的聲明的屬性和方法。
3、static方法調用static變量
1 public class Pvf { 2 static boolean Paddy; 3 public static void main(String[] args) { 4 System.out.println(Paddy); 5 } 6 7 }
輸出結果為false
分析:變量被賦予了默認值false。
4、static方法調用非static變量
1 public class Sytch { 2 int x = 20; 3 public static void main(String[] args) { 4 System.out.println(x); 5 } 6 7 }
輸出結果為:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field x
at test02.Sytch.main(Sytch.java:6)
5、
1 public class Sundys { 2 private int court; 3 public static void main(String[] args) { 4 Sundys s = new Sundys(99); 5 System.out.println(s.court); 6 } 7 Sundys(int ballcount) { 8 court = ballcount; 9 } 10 11 }
輸出結果為:99
分析:私有化變量仍可以被構造方法初始化。
6、私有化的一個應用是單例設計模式
1 class Singleton{ 2 private static Singleton instance = new Singleton(); 3 private Singleton(){ 4 } 5 public static Singleton getInstance(){ 6 return instance; 7 } 8 public void print(){ 9 System.out.println("hello"); 10 } 11 } 12 public class SingleDemo05 { 13 14 public static void main(String[] args) { 15 Singleton s1 = Singleton.getInstance(); 16 Singleton s2 = Singleton.getInstance(); 17 Singleton s3 = Singleton.getInstance(); 18 19 s1.print(); 20 s2.print(); 21 s3.print(); 22 23 } 24 25 }
輸出結果為:
hello
hello
hello
分析:雖然聲明了3個Singleton對象,但實際上所有的對象都只使用instance引用,也就是說,不管外面如何,最終結果也只有一個實例化對象存在。此即為單例設計模式。
由此可知,只要將構造方法私有化,就可以控制實例化對象的產生。