用類名定義一個變量的時候,定義的應該只是一個引用,外面能夠經過這個引用來訪問這個類裏面的屬性和方法。類裏面也有一個引用來訪問本身的屬性和方法,這個引用就是 this 對象,它能夠在類裏面來引用這個類的屬性和方法。java
每當一個對象建立後,Java虛擬機會給這個對象分配一個引用自身的指針,這個指針的名字就是 this。所以,this只能在類中的非靜態方法中使用,靜態方法和靜態的代碼塊中絕對不能出現this的用法。app
this主要要三種用法:ide
示例程序:函數
eg1工具
1 public class ThisDemo { 2 int number = 0; 3 ThisDemo increment(){ 4 number++; 5 return this; 6 } 7 private void print(){ 8 System.out.println("number="+number); 9 } 10 public static void main(String[] args) { 11 ThisDemo tt=new ThisDemo(); 12 tt.increment().increment().increment().print(); 13 } 14 } 15 /*Output: 16 i = 3 17 *///:~
能夠看到,經過this關鍵字能夠很容易在一條語句裏面對同一個對象執行屢次操做。this
eg2 將當前的對象傳遞給其餘方法spa
1 //: initialization/PassingThis.java 2 3 class Person { 4 public void eat(Apple apple) { 5 Apple peeled = apple.getPeeled(); 6 System.out.println("Yummy"); 7 } 8 } 9 10 class Peeler { 11 static Apple peel(Apple apple) { 12 // ... remove peel 13 return apple; // Peeled 14 } 15 } 16 17 class Apple { 18 Apple getPeeled() { return Peeler.peel(this); } 19 } 20 21 public class PassingThis { 22 public static void main(String[] args) { 23 new Person().eat(new Apple()); 24 } 25 } /* Output: 26 Yummy 27 *///:~
Apple須要調用Peeler.peel()方法,它是一個外部的工具方法,將執行因爲某種緣由而必須放在Apple外部的操做。爲了將其自身傳遞給外部方法,Apple必須使用this關鍵字。指針
eg3 在構造方法中引用知足指定參數類型的構造器code
1 //: initialization/Flower.java 2 // Calling constructors with "this" 3 import static net.mindview.util.Print.*; 4 5 public class Flower { 6 int petalCount = 0; 7 String s = "initial value"; 8 Flower(int petals) { 9 petalCount = petals; 10 print("Constructor w/ int arg only, petalCount= " 11 + petalCount); 12 } 13 Flower(String ss) { 14 print("Constructor w/ String arg only, s = " + ss); 15 s = ss; 16 } 17 Flower(String s, int petals) { 18 this(petals); 19 //! this(s); // Can't call two! 20 this.s = s; // Another use of "this" 參數s和數據成員s的名字相同,用this.s來避免歧義。 21 print("String & int args"); 22 } 23 Flower() { 24 this("hi", 47); 25 print("default constructor (no args)"); 26 } 27 void printPetalCount() { 28 //! this(11); // Not inside non-constructor! 29 print("petalCount = " + petalCount + " s = "+ s); 30 } 31 public static void main(String[] args) { 32 Flower x = new Flower(); 33 x.printPetalCount(); 34 } 35 } /* Output: 36 Constructor w/ int arg only, petalCount= 47 37 String & int args 38 default constructor (no args) 39 petalCount = 47 s = hi 40 *///:~
構造器Flower(String s, int petals)代表:儘管能夠用this調用一個構造器,但卻不能調用兩個。此外,必須將構造器調用置於最起始位置處,不然編譯器會報錯。對象
printPetalCount()方法代表,除構造器以外,編譯器禁止在其餘任何方法中調用構造器。
super的使用和this基本相同,如今寫下二者之間的比較:
1.super()從子類中調用父類的構造方法,this()在同一類內調用其它方法。
2.this和super不能同時出如今一個構造函數裏面。
3.super()和this()均需放在構造方法內第一行。
4.this()和super()都指的是對象,因此,均不能夠在static環境中使用。
另外1.在構造器中this或super必須放在第一行
另外2(static的含義)
瞭解this關鍵字以後,就能更全面的理解static方法的含義。static方法沒有this的方法。在static方法的內部不能調用非靜態方法,但反過來能夠。能夠在沒有建立任何對象的前提下,僅僅經過類自己來調用static方法。但這實際上正是static方法的主要用途。Java中禁止使用全局方法,但經過在類中置入static方法就能夠訪問其餘static方法和static域。