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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值