본문 바로가기

JAVA

07장- 객체지향 프로그래밍Ⅱ(5. 다형성) 21. 02. 18.

5. 다형성(polymorphism)

 

5.1 다형성이란?

- 객체지향개념에서 다형성이란 '여러 가지 형태를 가질 수 있는 능력'

- 자바에서는 한 타입의 참조변수로 여러 타입의 객체를 참조할 수 있도록 함으로써 다형성을 프로그램적으로 구현함.

-> 조상클래스 타입의 참조변수자손클래스의 인스턴스를 참조할 수 있도록 하였다는 것.

 

5.2 참조변수의 형변환

 

5.3 instanceof연산자

 

5.4 참조변수와 인스턴스의 연결

 

5.5 매개변수의 다형성

 

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

package ex0723;

import java.util.Vector;

import javax.swing.plaf.synth.SynthScrollBarUI;

class Product {
	int price;
	int bonusPoint; // 제품구매 시 제공하는 보너스점수

	Product(int price) {
		this.price = price;
		bonusPoint = (int) (price / 10.0);
	}

	Product() {
		price = 0;
		bonusPoint = 0;
	}
}

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";
	}
}

class Buyer { // 고객, 물건을 사는 사람
	int money  = 1000;
	int bonusPoint = 0;
	Vector item = new Vector(); // 구입한 제품을 저장하는데 사용될 Vector 객체
	
	void buy (Product p) {
		if(money < p.price) {
			System.out.println("잔액 부족");
			return;
		}
		money -= p.price;
		bonusPoint += p.bonusPoint;
		item.add(p);
		System.out.println(p + "를 구입.");
	}
	
	void refund (Product p) { // 구입한 제품 환불
		// 제품을 Vector에서 제거.
		if(item.remove(p)) {
			money += p.price;
			bonusPoint -= p.bonusPoint;
			System.out.println(p + "를 반품.");
		}
		else { // 제거 실패
			System.out.println("구입한 제품 중 해당 제품 없음.");
		}
	}
	
	void summary() { // 구매한 물품에 대한 정보 요약해서 보여줌.
		int sum = 0 ; // 구입한 물품의 가격합계
		String itemList = ""; // 구입한 물품목록
		
		if(item.isEmpty()) {
			System.out.println("구입한 제품 없음.");
			return;
		}
		// 반복문을 이용해서 구입한 물품의 총 가격과 목록 만듦.
		for (int i = 0 ; i < item.size() ; i++) {
			Product p = (Product)item.get(i);
			sum += p.price;
			itemList += (i == 0) ? "" + p : ", " + p;
		}
		System.out.println("구입한 물품 총 금액" + sum);
		System.out.println("구입한 제품" + itemList);
	}
}

class PolyArgumentTest3 {
	public static void main(String[] args) {
		Buyer b = new Buyer();
		Tv t = new Tv();
		Computer c = new Computer();
		Audio a = new Audio();
		
		b.buy(t);
		b.buy(c);
		b.buy(a);
		b.summary();
		System.out.println();
		b.refund(c);
		b.summary();

	}
}

PolyArgumentTest3.java