Java中this關鍵字的使用
說明:this用於指向調用該方法的當前對象。
用法:
1. this.成員變量 ------ 表示訪問當前對象的成員變量
2. this() ------ 表示調用另一個重載的構造函數
示例:
1. 在構造方法中,用來初始化成員變量的參數一般和成員變量取相同的名字,這樣有利於代碼的可讀性,但必須通過this關鍵字來區別成員變量和參數。
舉例:public class Cell{
int row;
int col;
public Cel(int row, int col){
this.row=row;
this.col=col;
}
}
2. 一個構造方法可以通過this關鍵字來調用另一個重載的構造方法
舉例:public class Cell{
int row;
int col;
public Cel(int row, int col){
this.row=row;
this.col=col;
}
public Cell(int x){
this
}
public Cell(){
this(1,1); //此處表示調用構造函數Cell(int row, int col),只不過row和col恰好都等於1而已。
}
}
Java中this關鍵字的使用