Java中toString()的使用

Java中提供了toString()方法,但如何使用?
先看個例子:

//代碼1

public class hw {
    public static void main(String[] args) {
        hw w = new hw();
        System.out.println(w.toString());
    }
}

打印出來的是類名加地址形式的字符串。

那麼如何對toString()方法進行使用?
再看一個例子:

//代碼2
public class Fan {
    final int slow = 1;
    final int medium = 2;
    final int fast = 3;

    public int speed = 1;
    public boolean on = false;
    public double radiu = 5;
    String color = "blue";

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        this.on = on;
    }

    public double getRadiu() {
        return radiu;
    }

    public void setRadiu(double radiu) {
        this.radiu = radiu;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String toString() {
        if (on == true) {
            return "fan is on: " + on +" "+ "[color: " + color + "]" + "[radius: " + radiu + "] " + "[speed: " + speed
                    + "] ";
        } else {
            return "fan is off:  " + "[color: " + color + "]" + " " + "[radius: " + radiu + "] ";
        }
    }

}


public class test {

    public static void main(String[] args) {
        Fan f1 = new Fan();
        f1.setSpeed(3);
        f1.setOn(true);
        f1.setRadiu(10);
        f1.setColor("yellow");

        Fan f2 = new Fan();
        f2.setOn(false);
        f2.setSpeed(2);
        f2.setRadiu(5);
        f2.setColor("blue");

        System.out.println(f1.toString());
        System.out.println(f2.toString());
        }
    }

從中看出調用toString()方法要對其進行重寫將原來的toString()方法覆蓋。

拓展閱讀:
各種面向對象程序語言的toString方法實現
http://blog.iderzheng.com/how-to-implement-tostring-in-different-languages/

JAVA中toString方法的作用
http://www.cnblogs.com/zhangjs8385/archive/2011/10/10/2205281.html

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