Java本身是一個物件導向程式語言,實作類別是家常便飯,接下來要說明的是如果把物件(Object)印出來,會觸發的函數功能。

下述的程式建立了一個 class,並且用這個 class 建立一個物件 person,並且灌入 person 建構子需要的變數。

並且將此物件印出來,一個是直接印物件,另一個則是將物件使用 toString() 函數印出來。

 

import java.io.Serializable;

public class SerializationSample {
	public static void main(String args[]){
		person Tom = new person(176.0,60.0);
		System.out.println(Tom);
		System.out.println(Tom.toString());
	}
}

class person implements Serializable{
	double height = 0;
	double weight = 0;
	public person(double height,double weight){
		this.height = height;
		this.weight = weight;
	}
}

下述是印出來的結果:

Test.person@15db9742
Test.person@15db9742

 

是的,你沒有看錯,兩個的確是一樣的值,這代表如果要直接印出物件,可以在該 class 中複寫 toString() 函數,程式碼如下:

import java.io.Serializable;

public class SerializationSample {
	public static void main(String args[]){
		person Tom = new person(176.0,60.0);
		System.out.println(Tom);
		System.out.println(Tom.toString());
	}
}

class person implements Serializable{
	double height = 0;
	double weight = 0;
	public person(double height,double weight){
		this.height = height;
		this.weight = weight;
	}
	
	public String toString(){
		return "Height: " + this.height + " Weight: " + this.weight;
	}
}

印出來的就會變成:

Height: 176.0 Weight: 60.0
Height: 176.0 Weight: 60.0

這樣在印物件的時候就方便許多。

arrow
arrow
    全站熱搜

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()