1. 程式人生 > >java中 this的用法

java中 this的用法

this關鍵字有三個主要的作用: 1、在構造方法中呼叫其他構造方法。比如有一個Person類,有三個構造方法,某一個建構函式中呼叫另外構造 方法,就要用到this,而直接使用Person()是不可以的。 2、返回當前物件的引用 3、區分成員變數和引數變數,解決區域性變數、引數變數與成員變數同名的問題。

public class Person {
     public String name;
     public int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
     public Person(){}
     public Person(String name){
    	 this();
    	 this.name =name;
     }
     public Person(String name,int age){
    	 this(name);
    	 this.age=age;
    	 
     }
     public static void main(String[] args){
    	 Person p=new Person("小明",15);
    	 p.setName("小明");
     }
}