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