Java & Kotlin
[Java 객체지향] 상속 활용 (멤버십 클래스 구현)
Sue
2022. 1. 30. 13:18
요구 사항
회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반고객(Customer)과 이보다 충성도가 높은 우수고객(VIPCustomer)에 따른 서비스를 제공하고자 함
물품을 구매 할때 적용되는 할인율과 적립되는 보너스 포인트의 비율이 다름
여러 멤버십에 대한 각각 다양한 서비스를 제공할 수 있음
멤버십에 대한 구현을 클래스 상속을 활용하여 구현해보기
Customer.java
- default 생성자를 이용해서 등급과 보너스 비율의 초기값을 정했다.
- 하위 클래스인 VIPCustomer에서 바꿔줄 멤버 변수 customerGrade는 protected로 설정
- 나머지 private 변수들은 getter와 setter를 만들어주었다.
package ch02;
public class Customer {
private int customerId;
private String customerName;
protected String customerGrade; // 하위 클래스에서는 접근 가능, 외부 클래스는 x
int bonusPoint;
double bonusRatio;
public Customer() {
customerGrade = "SILVER";
bonusRatio = 0.1;
}
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 int calcPrice(int price) {
bonusPoint += price * bonusRatio;
return price;
}
public String showCustomerInfo() {
return customerName + "님의 등급은 " + customerGrade + "이고, 보너스 포인트는 " + bonusPoint + "점 입니다.";
}
}
VIPCustomer.java
만약 새로운 등급을 추가하기 위해 Customer 클래스를 수정한다면 일반 고객들은 필요하지 않은 기능과 속성까지 추가해주어야 하고 중간에 등급을 구분하는 조건문(if)도 추가해야 한다. 또 다른 요구사항이 있을 때마다 계속 변경하게 되면 코드가 매우 복잡해지고 클래스의 단일성이 파괴된다. 때문에 따로 기능을 하는 클래스를 만들어주어야 한다. 만약 if - else if 문에서 분기가 많다면 상속을 고려해보자!
package ch02;
public class VIPCustomer extends Customer { // Customer 클래스 상속
private int agentId; // VIPCustomer 클래스의 속성 추가
private double saleRatio;
public VIPCustomer() {
customerGrade = "VIP";
bonusRatio = 0.5;
saleRatio = 0.1;
}
public int calcPrice(int price) {
bonusPoint += price * bonusRatio;
return (int)(price * (1 - saleRatio));
}
}
CustomerTest.java
package ch02;
public class CustomerTest {
public static void main(String[] args) {
Customer customerLee = new Customer();
customerLee.setCustomerName("Lee");
customerLee.setCustomerId(1000);
customerLee.bonusPoint = 1000;
System.out.println(customerLee.showCustomerInfo());
VIPCustomer customerKim = new VIPCustomer();
customerKim.setCustomerName("Kim");
customerKim.setCustomerId(1001);
customerKim.bonusPoint = 10000;
System.out.println(customerKim.showCustomerInfo()); // 상위 클래스의 메서드 사용
}
}
수행 결과
Lee님의 등급은 SILVER이고, 보너스 포인트는 1000점 입니다.
Kim님의 등급은 VIP이고, 보너스 포인트는 10000점 입니다.