{
String name;
public Person(String name)
{
this.name = name;
}
}
{
Component comp;
public void addComponent()
{
comp = new Component(this);
}
}
class Component
{
Container myContainer;
public Component(Container c)
{
myContainer = c;
}
}
3、構造方法是在產生對象時被java系統自動調用的,我們不能再程序中像調用其他方法一樣去調用構造方法。但我們可以在一個構造方法裏調用其他重載的構造方法,不是用構造方法名,而是用this(參數列表)的形式,根據其中的參數列表,選擇相應的構造方法。例如
{
String name;
int age;
public Person(String name)
{
this.name = name;
}
public Person(String name,int age)
{
this(name);
this.age = age;
}
}
1.this可指代對象自己本身: 當在一個類中要明確指出使用對象自己的屬性或方法時就應該加上this引用,如下例 子:
輸出的結果爲: Maybe=love you
this.Maybe=love
this.Maybe=love you
第一行直接對構造函數中傳遞過來的參數Maybe進行輸出,第二行是對成員變量(屬性) Maybe的輸出,第三行是先對成員變量(屬性)Maybe賦值後進行輸出。
2.在一個構造函數中調用另一個構造函數時,用this關鍵字:
以下例子:
private int petalCount=0;
private String s=new String("null");
public Flower(int petals){
petalCount=petals;
}
public Flower(String ss){
s=ss;
}
public Flower(String s,int petals){
this(petals); //java中在一個構造函數中可以調用一次其他的構造函數,並且這條語句 必須在這個構造函數的第一行
this.s=s;
}
}
String Maybe="love";
public love(String Maybe){
System.out.println("Maybe=" + Maybe);
System.out.println("this.Maybe="+this.Maybe);
this.Maybe=Maybe;
System.out.println("this.Maybe="+this.Maybe);
}
public static void main(String[] args){
love s=new love("love you");
}
}