void buy(Product p) { // 매개변수의 다형성. 메서드 하나로 여러 물건을 살 수 있다
money -= p.price;
bonusPoint += p.bonusPoint;
}
실습
class Product {
int price;
int bonusPoint; // 제품구매 시 제공하는 보너스점수
Product(int price){
this.price = price;
bonusPoint = (int)(price/10.0); // 보너스점수는 제품가격의 10%
}
}
class Tv extends Product {
Tv() {
// 조상클래스의 생성자 Product(int price)를 호출한다.
super(100); // Tv의 가격을 100으로 한다.
}
// Object 클래스의 toString()을 오버라이딩 한다.
public String toString() { return "Tv"; }
}
class Computer extends Product {
Computer() { super(200); }
public String toString() { return "Computer"; }
}
class Buyer {
int money = 1000;
int bonusPoint = 0;
void buy(Product p) { // 메서드 하나로 여러 물건을 살 수 있다. buy(new XX())
if(money < p.price) {
System.out.println("잔액 부족");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
System.out.println(p + "을/를 구입했습니다."); // p.toString() OK
}
}
public class practice {
public static void main(String[] args){
Buyer b = new Buyer();
Product p = new Tv();
b.buy(p);
// 위 두 문장을 아래와 같이 한 번에 나타낼 수 있다.
// b.buy(new Tv()); // buy(Product p)
b.buy(new Computer()); // buy(Product p)
System.out.println("현재 남은 돈은 " + b.money + "만원입니다.");
System.out.println("현재 보너스점수는 " + b.bonusPoint + "점입니다.");
}
}