본문 바로가기
개발공부/Java

[Java] 14. 객체 간의 상속

by sangyeon 2021. 12. 3.
728x90

1. 클래스 상속

- 새로운 클래스를 정의할 때 이미 구현된 클래스를 상속(inheritance) 받아서 속성이나 기능을 확장하여 클래스를 구현한다.

- 이미 구현된 클래스보다 더 구체적인 기능을 가진 클래스를 구현해야 할 때 기존 클래스를 상속함.

출처 - https://gitlab.com/easyspubjava/javacoursework

- 상속하는 클래스 : 상위 클래스, parent class, base class, super class라고 부름

- 상속받는 클래스 : 하위 클래스, child class, derived class, sub class라고 부름

 

상속의 문법

class B extends A{}

- extends 키워드 뒤에는 단 하나의 클래스만 올 수 있음

- 자바는 단일 상속만을 지원 함

 

 

2. 상속을 구현하는 경우

- 상속 클래스는 하위 클래스보다 더 일반적인 개념과 기능을 가짐

- 하위 클래스는 상위 클래스보다 더 구체적인 개념과 기능을 가짐

- 하위 클래스가 상위 클래스의 속성과 기능을  확장(extends)한다는 의미.

 

ex) 사람이 포유류 클래스를 상속받는다.

 

3. 상속을 활용한 멤버쉽 클래스 구현

멤버쉽 시나리오

회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반고객(Customer)과 
충성도가 높은 우수고객(VIPCustomer)에 따른 서비스를 제공하고자 함

물품을 구매할 때 적용되는 할인율과 적립되는 보너스 포인트의 비율이 다름
여러 멤버쉴에 대한 각각 다양한 서비스를 제공할 수 있음
멤버쉽에 대한 구현을 클래스 상속을 통해 구현해보자.

 

3-1. 일반고객(Customer) 클래스

- 고객의 속성 : 고객 ID, 고객 이름, 고객 등급, 보너스 포인트, 보너스 포인트 적립 비율

- 일반 고객의 경우 물품 구매시 1%의 보너스 포인트 적립

package ch02;

public class Customer {

protected int customerID;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;

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 Customer() {
customerGrade = "SILVER";
bonusRatio = 0.01;
}

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

public String showCustomerInfo() {
return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.";
}
}

 

3-2. 우수고객(VIPCustomer) 클래스

- Customer 클래스에 추가해서 구현하는 것은 좋지 않음

- VIPCustomer 클래스를 따로 구현

- 이미 Customer에 구현된 내용이 중복되므로 Customer를 확장하여(상속받아) 구현함

package ch02;

public class VIPCustomer extends Customer{

private int agentID; //우수 고객은 담당 상담원이 존재
double salesRatio;

public VIPCustomer() {
customerGrade = "VIP";
bonusRatio = 0.05;
salesRatio = 0.1;
}

//Annotation : 주석처럼 Override를 알리기 위함
//메소드 재정의
@Override
public int calcPrice(int price) {

bonusPoint += price * bonusRatio;
price -= (int)(price * salesRatio);
return price;
}

public int getAgentID() {
return agentID;
}

}

 

3-3. Client 코드 작성

package ch02;

public class CustomerTest {

public static void main(String[] args) {

int price = 0;

Customer customerLee = new Customer();
customerLee.setCustomerName("이순신");
customerLee.setCustomerID(10010);
customerLee.bonusPoint = 1000;
price = customerLee.calcPrice(1000);
System.out.println(customerLee.showCustomerInfo() + price);

VIPCustomer customerKim = new VIPCustomer();
customerKim.setCustomerName("김유신");
customerKim.setCustomerID(10020);
customerKim.bonusPoint = 10000;
price = customerKim.calcPrice(1000);
System.out.println(customerKim.showCustomerInfo() + price);
}

}
728x90