重寫toString()方法
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "我叫" + name + ",今年" + age + "歲。";
}
public static void main(String[] args) {
Student s1 = new Student("張三", 16);
System.out.println(s1);
Student s2 = new Student("李四", 19);
System.out.println(s2);
}
}
//////////////////////////////////////////////////////////////////////////////////////
class Apple {
String color;
String name;
double weight;
double price;
public Apple(String color, String name, double price, double weight) {
this.color = color;
this.name = name;
this.weight = weight;
this.price = price;
}
@Override
public String toString() {
return this.color + "的蘋果被稱為“" + this.name + "”, 每500克" + this.price + "元RMB,買了" + this.weight + "克,需支付" + (float)(this.price * (this.weight / 500)) + "元RMB。";
}
}
public class HongxinFSApple {
public static void main(String[] args) {
Apple apple = new Apple("紅色", "糖心富士", 4.98, 2500);
System.out.println(apple.toString());
}
}