在最近看書的過程當中,經常遇到static、final、this這三個關鍵字,不是很明白它們的使用,查閱資料結合實例作了以下總結:函數
1、static——無需建立對象就能夠調用(方法、屬性)。性能
1.靜態變量:static修飾的屬性,稱爲類屬性,即全局變量。前面已經有說起。學習
(1).靜態變量可使用類名直接訪問,也可使用對象名進行訪問。優化
1 class Number 2 { 3 int a; 4 static int b; 5 } 6 public class T01 7 { 8 public static void main(String[] args) 9 { 10 Number.a=5;//錯誤的 11 Number.b=6;//正確的,b是static修飾的靜態變量能夠直接用類名調用 12 } 13 }
(2).static不容許修飾局部變量:this
1 public static void max(int a,int b) 2 { 3 static int result;//Java中不被容許 4 }
(3).非靜態和靜態方法中都可以訪問static變量。spa
2.靜態方法:static修飾的方法,稱爲類方法。指針
(1).靜態方法中能夠調用類中的靜態變量,但不能調用非靜態變量。code
1 class Number 2 { 3 int a; 4 static int b; 5 public static void max(int c,int d) 6 { 7 int result; 8 result=a+b;//a是非靜態變量不能被靜態方法直接調用 9 10 } 11 }
那麼如何在靜態方法中調用非靜態變量呢?對象
1 class Number 2 { 3 int a; 4 static int b; 5 public static void max() 6 { 7 int result; 8 Number num = new Number(); 9 num.a=5; 10 result=num.a+b;//藉助對象調用非靜態變量a 11 System.out.println(result); 12 } 13 } 14 15 public class T01 16 { 17 public static void main(String[] args) 18 { 19 Number.b=6; 20 Number.max(); 21 } 22 }
(2).static方法沒有this—不依附於任何對象。blog
1 class Person 2 { 3 static String name; 4 static int age; 5 public static void print(String n,int a) 6 { 7 this.name=n;//錯誤的,靜態方法中沒法使用this 8 age=a; 9 } 10 }
3.靜態初始化塊—類加載時執行,且只會執行一次,只能給靜態變量賦值,不能接受任何參數。
1 class Number 2 { 3 static int a; 4 static int b; 5 public static void print() 6 { 7 int result; 8 result=a+b; 9 System.out.println(result); 10 } 11 static//static語句塊用於初始化static變量,是最早運行的語句塊 12 { 13 a=5; 14 b=8; 15 } 16 } 17 public class T01 18 { 19 public static void main(String[] args) 20 { 21 Number.print(); 22 } 23 }
由於static語句塊只會在類加載時執行一次的特性,常常用來優化程序性能。
2、final關鍵字——「只讀」修飾符
1.final和static一塊兒使用,聲明一個常量。
public static final int Age=10;//常量名大寫
final成員變量必須在聲明的時候初始化或在構造方法中初始化,不能再次賦值。
final局部變量必須在聲明時賦值。
2.final方法,這個方法不能夠被子類方法重寫。
1 class Person 2 { 3 public final String getName 4 { 5 return name; 6 } 7 }
3.final類,這種類沒法被繼承。
final class Person { }
4.final類不多是abstract的。
5.final和static同樣,合理的使用均可以提升程序性能。
3、this關鍵字——表明當前對象,封裝對象屬性
1.使用this調用本類中的成員變量。
public void setName(String name) { this.name=name;//相似於指針的做用 }
2.當成員變量和方法中的局部變量名字相同時,使用this調用成員變量。
3.this在方法內部調用本類中的其餘方法。
1 class Person 2 { 3 int age; 4 public void setAge(int age) 5 { 6 this.age=age; 7 this.print();//調用本類中的print()方法 8 } 9 public int getAge() 10 { 11 return age; 12 } 13 public void print() 14 { 15 System.out.println("我今年是:"+age+"歲"); 16 } 17 } 18 public class T01 19 { 20 public static void main(String[] args) 21 { 22 Person p = new Person(); 23 p.setAge(12); 24 } 25 }
4.this在方法中調用類的構造函數,必須位於第一行。
this(12,"Mary");//位於第一行
5.System.out.println(this);//輸出對象的地址
以上的內容簡單的歸納了static、final、this這三個關鍵字的大概使用,在從此的學習中會再次進行補充。
至於super關鍵字將會在接下來的繼承中介紹。