프로그램 문제

바이어 문제 - 다형성 적용

낙산암 2021. 10. 23. 20:15

public class Exercise7_19 {

public static void main(String[] args) {
    Buyer b = new Buyer();
    b.buy(new TV());
    b.buy(new Computer());
    b.buy(new TV());
    b.buy(new Audio());
    b.buy(new Computer());
    b.buy(new Computer());
    b.buy(new Computer());

    b.summary();
}

}

class Buyer {
int money = 1000;
Product[] cart = new Product[3];
int i = 0;

void buy(Product p) {

    if (money < p.price) {
        System.out.println("잔액이 부족하여 " + p.toString() + "을/를 살 수 없습니다.");
        return;
    }
    money = money - p.price;
    add(p);
}

void add(Product p) {

    if (i >= cart.length) {
        Product[] cart2 = new Product[cart.length * 2];
        System.arraycopy(cart, 0, cart2, 0, cart.length);
        cart = cart2;
    }

    cart[i] = p;
    i++;

}

void summary() {

    String list = "";
    int sum = 0;

    for (int i = 0; i < cart.length; i++) {
        if (cart[i] == null) {
            break;
        }
        list = list + cart[i] + ",";
        sum = sum + cart[i].price;
    }

    System.out.println("구입한 물건 : " + list);
    System.out.println("사용한 금액 : " + sum);
    System.out.println("남은 금액 : " + money);
}

}

class Product {
int price;

Product(int price) {
    this.price = price;
}

}

class TV extends Product {
TV() {
super(100);
}

public String toString() {
    return "TV";
}

}

class Computer extends Product {
Computer() {
super(200);
}

public String toString() {
    return "Computer";
}

}

class Audio extends Product {
Audio() {
super(50);
}

public String toString() {
    return "Audio";
}

}