public class OrderTest2 {
public static void main(String[] args) {
Order2 order1 = new Order2("Fried Rice", 2, 17);
Order2 order2 = new Order2("Fanta", 4, 6);
// order1 คือ Instance
// order2 คือ Instance
System.out.println("Order #1");
System.out.println(order1); // จะรู้อัตโนมัติว่าต้องไปเรียกใช้ ToString
System.out.println("Order #2");
System.out.println(order2); // จะรู้อัตโนมัติว่าต้องไปเรียกใช้ ToString
System.out.println("-----------------------------");
Order2.setVAT(8.0f);
System.out.println("Order #1\n" + order1);
System.out.println("Order #2\n" + order2);
}
}
class Order2 {
private static double vat = 7.0f;
private String name;
private int amount;
private double unitPrice;
public Order2(String n, int num, double price) {
if(n == null || num < 0 || price < 0)
throw new RuntimeException("program error");
name = n;
amount = num;
unitPrice = price;
}
public String toString() {
String str;
double total;
total = amount * unitPrice * (1+vat/100);
str = "Item name : " + name + "\n" +
"Amount : " + amount + " unit(s)\n" +
"Unit price : " + unitPrice + " baht\n" +
"VAT : " + vat + "%\n" +
"Total price : " + total + " baht\n";
return(str);
}
public static void setVAT(double v) {
if(v > 0)
vat = v;
}
}
No comments:
Post a Comment