我一直在使用多種方法,但是我的「java完整參考」一書並沒有很好的解釋如何使用「this」關鍵字。如何在java中使用「this」關鍵字?我不知道如何使用它?
-2
A
回答
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
區分a
和b
屬於對象從參數名稱,因爲它們是相同的屬性。
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
相關問題
- 1. Java - 何時使用'this'關鍵字
- 2. 在java中使用關鍵字「this」
- 3. 如何在java中使用靜態方法使用this關鍵字?
- 4. 如何知道應在哪裏使用AS關鍵字?
- 5. 何時在Java中使用「this」關鍵字?
- 6. 如何在JavaScript中使用關鍵字this?
- 7. 在JavaScript中使用「this」關鍵字
- 8. 我不知道如何使用Apache Ivy
- 9. 我不知道如何使用typedef enum
- 10. 我不知道如何使用@MapKey
- 11. 如何使用instanceof關鍵字Java
- 12. 我有一個結構,但我不知道如何使用它
- 13. 如何使用'this'關鍵字進行函數引用
- 14. 我應該在OOP編程中使用«this。»關鍵字來跳過它嗎?任何使用它的好處?
- 15. 什麼是預知關鍵字知道如:引用,:使用和:僅在Clojure中?
- 16. 如何使用關鍵字
- 17. 如何知道哪些對象可以在C#中使用關鍵字USING?
- 18. maven-qunit-plugin死了或者我不知道如何使用它?
- 19. PHP申請表 - 我不知道如何使用它
- 20. 什麼是在java中使用「this」關鍵字
- 21. 在Java構造函數中使用'this'關鍵字
- 22. 我如何在xna中使用c#鍵入關鍵字?
- 23. d3js - 如何使用`this`關鍵字或替代項是什麼?
- 24. 如何不使用final關鍵字
- 25. Angular JS - 什麼是'$ scope',它與使用'this'關鍵字相比如何?
- 26. 我不知道如何使用java gui/layouts?
- 27. 我不明白如何使用Java中的關鍵字NEW在這裏
- 28. 不知道有關使用Java
- 29. 我如何知道使用套接字使用UDP關閉了服務器
- 30. 我可以在c#.NET中強制使用'this'關鍵字嗎?
看教程http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – August 2014-09-27 15:23:23
我會感到驚訝,如果_完整的參考文獻_沒有解釋'this'。 – 2014-09-27 15:29:44
它用於構造函數,是否正確?它用了很多很好2知道*這*,* ahem * – Coffee 2014-09-27 15:49:25