상속 - 형변환, super()

겨울조아·2023년 3월 13일
0

super() 키워드

형변환

Customer.java

public class Customer {

	// 프라이빗하지만 하위클래스에게는 상속을 해주고 싶다 => protected
	protected int customerId;
	protected String customerName;
	protected String customerGrade;

	int bonusPoint;
	double bonusRatio; // 적립률

//	public Customer() {
//		customerGrade = "SILVER";
//		bonusRatio = 0.01;
//		
//		 System.out.println("Customer() call");
//	}

	// super(); 알아보기 위해
	// 디폴트 생성자 없애고 매개 변수가 있는 생성자 추가
	public Customer(int customerId, String customerName) {
		this.customerId = customerId;
		this.customerName = customerName;

		customerGrade = "SILVER";
		bonusRatio = 0.01;

		System.out.println("Customer(int, String) call");
	}

	// String agentID; vip 관리
	// => 복잡함 그래서 클래스 분리가 좋음

	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price;
	}

	public int getCustomerId() {
		return customerId;
	}
	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}
	public String getCustomerName() {
		return customerName;
	}
	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
	public String getCustomerGrade() {
		return customerGrade;
	}
	public void setCustomerGrade(String customerGrade) {
		this.customerGrade = customerGrade;
	}
	public String showCustomerInfo() {
		return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.";
	}
}

VIPCustomer.java

public class VIPCustomer extends Customer {

	private static int agentID;
	double salesRatio;

	public VIPCustomer(int customerId, String customerName) {

		super(customerId, customerName);
		// super();
		// 쓰지 않아도 알아서 하위클래스가 항상 상위클래스의 생성자를 호출
		customerGrade = "VIP";
		salesRatio = 0.05;
		bonusRatio = 0.1;

		System.out.println("VIPCustomer(int, String) call");
	}

	public int getAgentId() {
		agentID++;
		return agentID;
	}
}

CustomerTest.java

public class CustomerTest {

	public static void main(String[] args) {

//		Customer customerLee = new Customer();
//		customerLee.setCustomerName("이순신");
//		customerLee.setCustomerId(10010);
//		customerLee.bonusPoint = 1000;
//		System.out.println(customerLee.showCustomerInfo());

		// Customer() call 이후에 VIPCustomer() call
		// 상위 먼저 호출됨
        // 형변환!!
		Customer customerKim = new VIPCustomer(10020, "김유신");
		customerKim.bonusPoint = 10000;
		System.out.println(customerKim.showCustomerInfo());

//		VIPCustomer customerChoi = new VIPCustomer();
//		System.out.println(customerChoi.getAgentId());
	}
}

0개의 댓글