java 必須用this的幾種情況
摘抄自張孝祥老師的 java就業培訓教程。
this只存在與方法內部,用來代表呼叫改方法的物件。可以理解為每一個方法內部都有一個區域性變數叫this,每當初始化一個物件時,就把該物件的地址傳遞給了該物件每一個方法中的this變數,從而可以在方法內部使用這個的物件。
第一種情況:
建構函式中物件成員變數的初始化時使用,用來區分成員變數跟形式引數
public class StudyThis { private String name; private int age; public StudyThis(String name,int age){ this.name=name; this.age=age; } }
第二種情況:
假設有兩個類,容器類Container和內容類Component,在Container的成員方法中需要呼叫Component類的一個物件。Component的建構函式中需要一個呼叫它的Container類作為引數。
第三中情況class Container{ Component comp; public void addComponent(){ comp=new Component(this); } } class Component{ Container myContainer; public Component(Container c){ myContainer=c; } }
構造方法不能想其他方法一樣被呼叫,只能在系統初始化一個物件時被系統呼叫。雖然構造方法不能被其他函式呼叫,但是可以被該類的其他構造方法呼叫,這時用this即可。
class Person{
int age;
String name;
public Person(){
}
public Person(int age){
this.age=age;
}
public Person(int age,String name){
this(age);
this.name=name;
}
}