java基礎之this的用法 10.13

this:
1.返回調用當前方法的對象的引用。
public class Leaf{
private int i=0;
public Leaf increament(){
i++;
return this;
}
public static void main(String[] args){
Leaf x= new Leaf();
x.increment().print();
Leaf y= new Leaf();
y.increment().print();
}
}this

this表示Leaf類的實例 當執行x.increment(),this表示實例x的引用。同理執行y.increment(),this表示實例y的引用。對象

2.在構造方法中調用當前類的其餘構造方法.
定義了3個person類的構造方法,分別是無參,有一個參數,有兩個參數,實現代碼的重複利用,使用this()和this(_name)來調用person()和person(String _name)
在使用this調用其餘的構造方法時,必須放在構造方法的開始處,否咋不會編譯
public class Person{
private String name;
private int age;
private String sex;
public Person(){
sex="male";
}
public Person(String _name){
this();
name=_name;
}
public Person(String _name,int _age){
this(_name);
age=_age;
}
}
3.當方法參數名和成員變量名相同,用於區分參數名和成員變量。
setter方法的參數名和成員變量名相同,this.name表示成員變量名,name表示參數名。
public class Person{
private String name;
privae int age;
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
}rem

相關文章
相關標籤/搜索