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我是萌新啊
添加回答
舉報
0/150
提交
取消