Java

69. 여러 종류의 객체를 배열로 다루기 - 패스트캠퍼스 백엔드 부트캠프 3기

gkss2tpt 2024. 12. 23. 11:50

1. 여러 종류의 객체를 배열로 다루기

  • 조상타입의 배열에 자손들의 객체를 담을 수 있다.
Product p1 = new Tv();
Product p2 = new Computer();
Product p3 = new Audio();

Product[] p = new Product[3];
p[0] = new Tv();
p[1] = new Computer();
p[2] = new Audio();

class Buyer {
    int money = 1000;
    int bonusPoint = 0;
    
    Product[] cart = new Product[10];	// 구입한 물건을 담을 배열
    
    int i = 0;
    
    void buy(Product p) {
    	if(money < p.price) {
        	System.out.println("잔액부족");
            return;
        }
        
        money -= p.price;
        bonusPoint += p.bonusPoint;
        cart[i++] = p;	// 카트에 저장 
    }
}