Java中this的簡單應用

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章