一般都是对自身信息的描述:
输出一个对象,对于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);//结果和上面一句一样的
}
}