본문 바로가기
JAVA

[JAVA] 가상 메서드

by watergrace2u 2022. 3. 24.
반응형
SMALL

 

타입과 상관없이 실제 생성된 인스턴스의 메서드가 호출된다!!

 

class Customer {
	protected int customerID;
	protected String customerName;
	protected String customerGrade;
	
	int bonusPoint;
	double bonusRatio;
	
	public Customer(int customerID,String customerName ) {
		this.customerID = customerID;
		this.customerName = customerName;
		customerGrade = "SILVER";
		bonusRatio= 0.01;	
	}
    
	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price;
	}
    
	public String showCustomerInfo() {
		return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint+"입니다.";
	}
}

class VIPCustomer extends Customer {
	private int agentID;
	private double saleRatio;
	
	public VIPCustomer(int customerID,String customerName, int agentID) {
		super(customerID,customerName);
		customerGrade = "VIP";
		bonusRatio = 0.05;
		saleRatio = 0.1;
		this.agentID = agentID;
	}
	
	@Override
	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price - (int) (price*saleRatio);
	}
}

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

		// VIPCustomer 것이 불렸다!
		Customer who = new VIPCustomer(14028,"Who",10000);
		price = who.calcPrice(10000);		
		System.out.println("지불 금액은 "+price+"원 입니다. "+ who.showCustomerInfo());
				
	}
}

출력 결과

 

cf. do it 자바 프로그래밍 인프런 강의

반응형
LIST

'JAVA' 카테고리의 다른 글

[JAVA] 다운캐스팅  (0) 2022.03.27
[JAVA] 다형성 (Polymorphism)  (0) 2022.03.24
[JAVA] 상위 클래스로 묵시적 형변환 (업캐스팅)  (0) 2022.03.24
[JAVA] 접근 제한자  (0) 2022.03.24
[JAVA] ArrayList 클래스  (0) 2022.03.24

댓글