본문 바로가기
JAVA

[JAVA] 상위 클래스로 묵시적 형변환 (업캐스팅)

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

 

 

- 하위 클래스가 생성될 때, 상위 클래스가 항상 먼저 생성된다.

- 하위 클래스가 상위 클래스의 타입을 내포하기 때문에, 상위 클래스로 묵시적 형변환이 가능하다. 

- VIPCustomer() 생성자의 호출로 인스턴스는 모두 생성되었지만, 타입이 Customer 이므로 접근할 수 있는 변수나 메서드는 Customer의 변수와 메서드이다!

 

package ClassPart;

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.1;
		
	}
    
	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) {
    
		super(customerID,customerName);
		customerGrade = "VIP";
		bonusRatio = 0.05;
		saleRatio = 0.1;
	}
}

public class CustomerTest {
	public static void main(String [] args) {
    
		Customer haeun = new Customer(14027,"haeun");
		haeun.bonusPoint = 10000;		
		Customer song = new VIPCustomer(14028,"song");
		song.bonusPoint = 20000;

		System.out.println(haeun.showCustomerInfo());
		System.out.println(song.showCustomerInfo());
	}

}

출력 결과

 

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

반응형
LIST

'JAVA' 카테고리의 다른 글

[JAVA] 다형성 (Polymorphism)  (0) 2022.03.24
[JAVA] 가상 메서드  (0) 2022.03.24
[JAVA] 접근 제한자  (0) 2022.03.24
[JAVA] ArrayList 클래스  (0) 2022.03.24
[JAVA] 객체 배열의 깊은 복사  (0) 2022.03.23

댓글