public class Apple {
private String color;
private double weight;
public Apple() {}
//提供有参数的构造器
public Apple(String color,double weight) {
this.color=color;
this.weight=weight;
}
//省略color、weight的srtter和getter方法
//重写toString()方法,用于实现Apple对象的“自我描述”
public String toString() {
return"一个苹果,颜色是:"+color+",重量是:"+weight;
}
}
public class ToStringTest {
public static void main(String[]args) {
Apple a=new Apple("红色",5.68);
//打印Apple对象
System.out.println(a);
}
}
输出结果:一个苹果,颜色是:红色,重量是:5.68
我是萌新啊