1. 程式人生 > >重寫toString方法的好處

重寫toString方法的好處

舉例:比如一個java類,未重寫toString方法:

public class TableInfo {
	
    private String tableID;
    private String tableName;
    private int tableState;
 
    public String getTableID() {
		return tableID;
	}

	public void setTableID(String tableID) {
		this.tableID = tableID;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public int getTableState() {
		return tableState;
	}

	public void setTableState(int tableState) {
		this.tableState = tableState;
	}
}
新建一個該類的物件,並直接輸出:

[email protected]

這是一個地址,而不是物件本身,如果重寫了toString方法:

public class TableInfo {
	
    private String tableID;
    private String tableName;
    private int tableState;
 
    public String getTableID() {
		return tableID;
	}

	public void setTableID(String tableID) {
		this.tableID = tableID;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public int getTableState() {
		return tableState;
	}

	public void setTableState(int tableState) {
		this.tableState = tableState;
	}

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("TableInfo{");
        sb.append("TableID='").append(tableID).append('\'');
        sb.append(", TableName='").append(tableName).append('\'');
        sb.append(", TableState=").append(tableState);
        sb.append('}');
        return sb.toString();
    }
}
再次輸出:

TableInfo{TableID='0101', TableName='101桌', TableState=0}

是不是感覺有點用處~