Java toString()方法

每個非基本類的對象都有一個toString()方法,若編輯器本來希望的是一個String,但獲得的卻是某個這樣的對象,就會調用這個方法。如果我們創建一個允許這種行爲的類時,就需要寫一個toString()方法。

//類再生,合成的語法

class Soap{
	private String s;
	Soap(){
		System.out.println("Soap");
		s = new String("Constructed");
	}
	public String toString(){
		return s;
	}
}


public class Bath {
	
	Soap castille;
	
	Bath(){
		System.out.println("Inside Bath()");
		castille = new Soap();
	}
	
	void print(){
		System.out.println("castille = " + castille);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Bath b = new Bath();
		b.print();
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章