類變量(static)
類變量是該類的所有對象共享的變量,任何一個該類的對象去訪問它時,取到的都是相同的值,同樣任何一個該類的對象去修改它時,修改的也是同一個變量。
1 public class C { 2 public static void main(String[] args){ 3 4 Child ch1 = new Child(12,"小小"); 5 ch1.joinGame(); 6 Child ch2 = new Child(13,"小紅"); 7 ch2.joinGame(); 8 //調用類變量 9 System.out.println("一共有" + Child.total+ "小朋友"); 10 } 11 } 12 13 class Child{ 14 public int age; 15 public String name; 16 17 //total是靜態變量,因此他可以被任何類調用 18 public static int total = 0; 19 20 public Child(int age, String name) 21 { 22 this.age = age; 23 this.name = name; 24 } 25 26 public void joinGame() 27 { 28 total++; 29 System.out.println("有一個小朋友加進來!"); 30 } 31 }
運行結果
靜態區塊
只要程序啟動就會被執行一次,也僅執行一次
1 public class C { 2 3 static int i = 1; 4 static 5 { 6 System.out.println("靜態區域塊被執行一次"); 7 //該靜態區域塊,只被執行一次,也不會因創建對象而觸發 8 i++; 9 } 10 public C() 11 { 12 System.out.println("構造函數域塊被執行一次"); 13 i++; 14 } 15 16 public static void main(String[] args){ 17 18 C t1 = new C(); 19 System.out.println("輸出第一個i的值為:" + C.i); 20 C t2 = new C(); 21 System.out.println("輸出第二個i的值為:" + C.i); 22 } 23 }
運行結果
類方法
類方法中不能訪問非靜態變量
1 public class C { 2 public static void main(String[] args){ 3 Student stu1 = new Student(18,"小紅",580); 4 Student stu2 = new Student(18,"小黑",620); 5 System.out.println("有" + Student.p_total + "個學生"); 6 System.out.println("學費總收入:" + Student.get_total_fee()); 7 } 8 } 9 10 //定義一個學生類 11 class Student{ 12 public int age; 13 public String name; 14 public double fee; //學費 15 public static int p_total = 0; 16 public static double total_fee; //總學費 17 18 public Student(int age, String name, double fee) 19 { 20 p_total++; 21 this.age = age; 22 this.name = name; 23 this.total_fee += fee; 24 } 25 26 //靜態方法 27 //Java中規則:類變量原則上用類方法去訪問 28 public static double get_total_fee() 29 { 30 return total_fee; 31 } 32 }
運行結果
匿名對象
就是沒有名字的對象,當對象僅進行一次調用的時候,就可以簡化成匿名對象。
1 //舉例 2 new Car().run();