this關鍵字做用:
1. 若是存在同名成員變量與局部變量時,在方法內部默認是訪問局部變量的數據,能夠經過this關鍵字指定訪問成員變量的數據。
2. 在一個構造函數中能夠調用另一個構造函數初始化對象。函數
this關鍵字調用其餘的構造函數要注意的事項:
1. this關鍵字調用其餘的構造函數時,this關鍵字必需要位於構造函數中 的第一個語句。
2. this關鍵字在構造函數中不能出現相互調用 的狀況,由於是一個死循環。this
/** * Created by qic on 2018/4/13. */ public class Student { int id; //身份證 String name; //名字 //目前狀況:存在同名 的成員 變量與局部變量,在方法內部默認是使用局部變量的。 public Student(int id,String name){ //一個函數的形式參數也是屬於局部變量。 this(name); //調用了本類的一個參數的構造方法 //this(); //調用了本類無參的 構造方法。 this.id = id; // this.id = id 局部變量的id給成員變量的id賦值 System.out.println("兩個參數的構造方法被調用了..."); } public Student(){ System.out.println("無參的構造方法被調用了..."); } public Student(String name){ this.name = name; System.out.println("一個參數的構造方法被調用了..."); } } class Demo7 { public static void main(String[] args) { Student s = new Student(110,"鐵蛋"); System.out.println("編號:"+ s.id +" 名字:" + s.name); } }