2014-09-27 108 views
-2

我一直在使用多種方法,但是我的「java完整參考」一書並沒有很好的解釋如何使用「this」關鍵字。如何在java中使用「this」關鍵字?我不知道如何使用它?

+1

看教程http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – August 2014-09-27 15:23:23

+0

我會感到驚訝,如果_完整的參考文獻_沒有解釋'this'。 – 2014-09-27 15:29:44

+0

它用於構造函數,是否正確?它用了很多很好2知道*這*,* ahem * – Coffee 2014-09-27 15:49:25

回答

0

這裏有一對夫婦:

public class Example { 
    private int a; 
    private int b; 

    // use it to differentiate between local and class variables 
    public Example(int a, int b) { 
     this.a = a; 
     this.b = b; 
    } 

    // use it to chain constructors 
    public Example() { 
     this(0, 0); 
    } 

    // revised answer: 
    public int getA() { 
     return this.a; 
    } 

    public int getB() { 
     return this.b 
    } 

    public int setA(int a) { 
     this.a = a 
    } 

    public void setB(int b) { 
     this.b = b; 
    } 
} 

this是指屬於中this在使用對象的屬性,例如:

Example ex1 = new Example(3,4); 
Example ex2 = new Example(8,1); 

在這些情況下,ex1.getA()將返回3 ,因爲this指的是屬於名爲ex1的對象的a,而不是ex2或其他任何內容。 ex2.getB()也是如此。

如果你看一下setA()setB()方法,使用this區分ab屬於對象從參數名稱,因爲它們是相同的屬性。

在Java
+0

你能解釋什麼「這個」關鍵字用於?我不知道該怎麼處理它 – petor 2014-09-27 17:04:52

+0

'this'是對自己的引用 – Alex 2014-09-27 17:56:03

+0

對不起,但是什麼是「本身」 – petor 2014-10-29 04:33:04

1

它是用來指在envoked方法或構造對象的數據成員的情況下,有字段和局部變量

public class Test { 
    String s; 
    int i; 
    public Test(String s, int i){ 
     this.s = s; 
     this.i = i; 
    } } 

它是間名稱衝突用於從同一個類的另一個構造函數調用一個構造函數,或者可以說構造函數鏈。

public class ConstructorChainingEg{ 
    String s; 
    int i; 
    public ConstructorChainingEg(String s, int i){ 
     this.s = s; 
     this.i = i; 
     System.out.println(s+" "+i); 
    } 
    public ConstructorChainingEg(){ 
     this("abc",3); // from here call goes to parameterized constructor 
    } 

    public static void main(String[] args) { 
     ConstructorChainingEg m = new ConstructorChainingEg(); 
     // call goes to default constructor 
    } 
} 

這也促進法鏈

class Swapper{ 
    int a,b; 
    public Swapper(int a,int b){ 
     this.a=a; 
     this.b=b; 
    } 
    public Swapper swap() { 
     int c=this.a; 
     this.a=this.b; 
     this.b=c; 
     return this; 
    } 
    public static void main(String aa[]){ 
     new Swapper(4,5).swap(); //method chaining 
    } 
} 
+0

在'main'方法中最後一個例子,你可以將'Swapper'賦值給一個變量(或者做類似的事情),這樣'return this'就可以使用。 – 2014-09-27 16:02:10

+0

所以「this」用於多個構造函數?如果是這樣,那麼爲什麼你需要多個構造函數? – petor 2014-09-27 20:33:47

相關問題