컴퓨터공학 💻 도서관📚
Part2. 3-2 상속을 활용한 멤버십 클래스 구현하기 본문
회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반고객(Customer)과
이보다 충성도가 높은 우수고객(VIPCustomer)에 따른 서비스를 제공하고자 한다
물품을 구매 할때 적용되는 할인율과 적립되는 보너스 포인트의 비율이 다르다
여러 멤버십에 대한 각각 다양한 서비스를 제공할 수 있다
멤버십에 대한 구현을 클래스 상속을 활용하여 구현해보자
일반 고객(Customer) 클래스 구현
* 고객의 속성 : 고객 아이디, 고객 이름, 고객 등급, 보너스 포인트, 보너스 포인트 적립비율
* 일반 고객의 경우 물품 구매 시 1%의 보너스 포인트 적립
package ch01;
public class Customer {
protected int customerID;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
public Customer() {
customerGrade = "SILVER";
bonusRatio = 0.01; // 값이 고정이므로 생성자에서 초기화
}
public int calcPrice(int price) { // 구매 시 보너스 포인트 적립
bonusPoint += price * bonusRatio;
return price;
}
// get, set 메서드 시작
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;
}
// get, set 메서드 끝
public String showCustomerInfo() {
return customerName + "님의 등급은 " + customerGrade +
"이며, 보너스 포인트는" + bonusPoint + "입니다";
}
}
우수 고객(VIPCustomer) 구현
* 매출에 더 많은 기여를 하는 단골 고객
* 제품을 살 때 10%를 할인해 줌
* 보너스 포인트는 제품 가격의 5%를 적립해 줌
* 담당 전문 상담원이 배정됨
Customer 클래스에 추가해서 구현하는 것은 좋지 않음
VIPCustomer 클래스를 따로 구현
이미 Customer에 구현된 내용이 중복되므로 Customer를 확장하여 구현함 (상속)
if else if else 가 어떤 조건에 의해 굉장히 많다면 이건 상속을 한번 생각해 볼 여지가 있다
public class VIPCustomer extends Customer{
private int agentID;
double salesRatio;
public VIPCustomer() {
customerGrade = "VIP"; // 상위 클래스에서 이 변수가 private, default 면 오류 발생한다
bonusRatio = 0.05;
salesRatio = 0.1;
}
public int getAgentID() {
return agentID;
}
}
protected 접근 제어자 활용
* 상위 클래스에 선언된 private 멤버 변수는 하위 클래스에서 접근 할 수 없음
* 외부 클래스는 접근 할 수 없지만, 하위 클래스는 접근 할 수 있도록 protected 접근 제어자를 사용
protected int customerID;
protected String customerName;
protected String customerGrade; // 이 변수가 private, default 면 하위 클래스에서 사용 못 한다
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());
VIPCustomer customerKim = new VIPCustomer();
customerKim.setCustomerName("김유신");
customerKim.setCustomerID(10020);
customerKim.bonusPoint = 10000;
System.out.println(customerKim.showCustomerInfo());
}
}
'✅🌲강의 복습 노트 > 패캠 JavaSpring 강의,코드 복습' 카테고리의 다른 글
Part2. 3-4 메서드 재정의하기 (overriding) (0) | 2025.05.22 |
---|---|
Part2. 3-3 상속에서 클래스 생성 과정과 형 변환 (0) | 2025.05.22 |
Part2. 3-1 객체 간의 상속의 의미 (0) | 2025.05.20 |
Part2. 2-24. ArrayList를 활용한 간단한 성적 산출 프로그램 (0) | 2025.05.20 |
Part2. 2-23 객체 배열을 구현한 클래스 ArrayList (리스트) (1) | 2025.05.19 |
Comments