1.局部變量與成員變量同名的情況下
Person(String name, int age){
this.name = name;//this.name指代的是類裏定義的name而不是Person這個函數的參數。
this.age = age;
}
2.需要用this指代當前的對象,return this
calss Person{
int age=0;
Person grow(){
age++;
return this;
}
void print(){
System.out.println("My age is:"+age);
}
class Demo{
public static void main(String args[]){
Person p = new Person();
p.grow().grow().grow().speak();
}
}
}
輸出:My age is:3