一般都是对自身信息的描述:
输出一个对象,对于toString可以省略,结果是一样的
package tostring;
/**
* Date:2019/9/21
* Author:zkh
* DESC:
*/
public class Apple {
private String color;
private int weight;
public Apple(){
}
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String toString(){
return "一个苹果的颜色是:"+color+",重量是:"+weight;
}
}
package tostring;
/**
* Date:2019/9/21
* Author:zkh
* DESC:
*/
public class ToStringDemo {
public static void main(String[] args) {
Apple apple = new Apple("红色", 56);
System.out.println(apple.toString());//结果和下面一句一样的
System.out.println(apple);//结果和上面一句一样的
}
}
本文详细介绍了Java中对象的toString方法实现,通过一个具体的Apple类示例,展示了如何自定义toString方法来返回对象的状态信息,这对于调试和理解对象在运行时的状态非常有用。
13万+

被折叠的 条评论
为什么被折叠?



