1. 程式人生 > >JAVA程式設計思想(第4版) 在構造器中呼叫構造器

JAVA程式設計思想(第4版) 在構造器中呼叫構造器

可能為一個類寫了多個構造器,為了能夠在一個構造器中呼叫另一個構造器,必須用到this關鍵字,this指"這個物件",表示對當前物件的引用。舉個例子:

package test;

public class Flower {
	int petalCount=0;
	String s="initial value";
	Flower(int petals){
		petalCount=petals;
		System.out.println("Constructor w/ int arg only,petalCount= "+petalCount);
	}
	Flower(String ss){
		System.out.println("Constructor w/ String arg only,s= "+ss);
		s=ss;
	}
	Flower(String s,int petals){
		this(petals);//構造器的呼叫必須是該構造器中的第一個語句
		//! this(s);//不能同時呼叫倆個構造器
		this.s=s;
		System.out.println("String &int args");
	}
	Flower(){
		this("hello",48);
		System.out.println("default constructor(no args)");
	}
	void printPetalCount(){
		//!this(10);//不能在非構造器類中呼叫構造器
		System.out.println("petalCount= "+petalCount+" s= "+s);
	}
	public static void main(String[] args) {
		
		Flower x=new Flower();
		x.printPetalCount();
	}
}

執行結果如圖:


小結:

1.構造器Flower(String s,int petals)表明需要將構造器的呼叫置於該構造器的第一個語句,從而利用this呼叫構造器,但是不能同時呼叫倆個構造器

2.方法printPetalCount()表明不能在非構造器類中呼叫構造器,而且編譯器禁止在除構造器的其他任何地方呼叫構造器