본문 바로가기
study/Java

[Java] 22. 상속 Exam2 (각 클래스를 생성하고 출력하기)

by 금이패런츠 2022. 3. 21.
728x90
반응형
package chap7;
/*
 * Product 클래스
 *  멤버변수 : 가격, 포인트
 *  생성자 : 가격을 입력받고, 가격의 10%포인트로 저장
 * Tv 클래스 
 *   생성자 : 가격을 100 설정하기
 *   toString : "Tv" 리턴
 * Computer 클래스 
 *   생성자 : 가격을 200 설정하기
 *   toString : "Computer" 리턴
 */
class Product {    //product 클래스
	int price, point;
	Product(int price) {
		this.price = price;
		point = price/10;
	}
}
class Tv extends Product { //product에서 상속받는 클레스
	Tv() {
		super(100);
	}
	public String toString() {
		return "Tv";
	}
}
class Computer extends Product {
	Computer() {
		super(200);
	}
	public String toString() {
		return "Computer";
	}
}
/*
 * Buyer 클래스
 *   멤버변수 : money=500, point
 *           Product[] items = new Product[5];
 *           int cnt;
 *   멤버 메서드
 *      void buy(Product p)
 *      1. p 상품의 가격을 money에서 차감
 *      2. p 상품의 point를 나의 point에 더함
 *      3. items에 p 제품을 추가. cnt 증가
 *      4. p 제품을 출력        
 */
class Buyer {
	int money = 500;
	int point;
	//items : Product객체의 배열.
	Product[] items = new Product[5];
	int cnt;
	void buy(Product p) { //Product : Tv, Computer 클래스가 자동형변환이 가능
		money -= p.price; //          Tv, Computer 클래스의 부모클래스
		point += p.point;
		items[cnt++] = p;
		System.out.println(p + "구입");
	}
}
public class Exam2 {
	public static void main(String[] args) {
		Tv tv = new Tv();
		Computer cm = new Computer();
		Buyer b = new Buyer();
		b.buy(tv);
		b.buy(cm);
		System.out.println("고객의 잔액:" + b.money);
		System.out.println("고객의 포인트:" + b.point);
		System.out.print("구매제품:");
		for(Product p : b.items) {
			if (p != null)
			System.out.print(p + ",");
		}
		System.out.println();
	}
}
728x90
반응형

'study > Java' 카테고리의 다른 글

[Java] 23. 패키지  (0) 2022.03.21
[Java] 23. 추상클래스 (abstract)  (0) 2022.03.21
[Java] 22. instanceof 연산자  (0) 2022.03.21
[Java] 22. 상속2  (0) 2022.03.21
[Java] 22. 자바용어정리  (0) 2022.03.21