Java

[Java] 다형성 활용하기

코딩하는 붕어 2021. 2. 20. 02:43
반응형

▶ 일반 고객과 VIP 고객의 중간 등급 만들기

package witharraylist;

public class GoldCustomer extends Customer {
	double saleRatio;

	public GoldCustomer(int customerID, String customerName) {
		super(customerID, customerName);
		customerGrade = "GOLD";
		bonusRatio = 0.02;
		saleRatio = 0.1;
	}

    @Override
	public int calcPrice(int price) {  // 재정의된 메서드
		bonusPoint += price * bonusRatio;
		return price - (int) (price * saleRatio);
	}
}

-Customer 클래스를 패키지로 복사해올것.

 

 

▶ 배열로 고객 5명 구현하기

package witharraylist;

import java.util.ArrayList;

public class CustomerTest {
	public static void main(String[] args) {

		ArrayList<Customer> customerList = new ArrayList<Customer>();

		Customer customerLee = new Customer(10010, "이순신");
		Customer customerShin = new Customer(10020, "신사임당");
		Customer customerHong = new GoldCustomer(10030, "홍길동");
		Customer customerYul = new GoldCustomer(10040, "이율곡");
		Customer customerKim = new VIPCustomer(10050, "김유신", 12345);

		customerList.add(customerLee);
		customerList.add(customerShin);
		customerList.add(customerHong);
		customerList.add(customerYul);
		customerList.add(customerKim);

		System.out.println("====== 고객 정보 출력 =======");

		for (Customer customer : customerList) {
			System.out.println(customer.showCustomerInfo());
		}

		System.out.println("====== 할인율과 보너스 포인트 계산 =======");

		int price = 10000;
		for (Customer customer : customerList) {  // 다형성 구현
			int cost = customer.calcPrice(price);
			System.out.println(customer.getCustomerName() + " 님이 " + cost + "원 지불하셨습니다.");
			System.out.println(customer.getCustomerName() + " 님의 현재 보너스 포인트는 " + customer.bonusPoint + "점입니다.");
		}
	}
}

 

<실행 결과>

 

반응형