객체 간의 상속은 어떤 의미일까?
클래스 상속
새로운 클래스를 정의할 때 이미 구현된 클래스를 상속 받아서 속성이나 기능을 확장해 클래스를 구현한다. 이미 구현된 클래스보다 더 구체적인 기능을 가진 클래스를 구현할 때 기존 클래스를 상속한다. |
상속하는 클래스: 상위 클래스, parent class, base class, super class 상속 받는 클래스: 하위 클래스, child class, derived class, subclass |
상속 문법
class B extends A {
}
extends 키워드 뒤에는 단 하나의 클래스만 올 수 있다. 자바는 단일 상속 single inheritance 만을 지원한다. |
상속을 구현하는 경우
상위 클래스는 하위 클래스보다 더 일반적인 개념과 기능을 가진다. 하위 클래스는 상위 클래스보다 더 구체적인 개념과 기능을 가진다. 하위 클래스가 상위 클래스의 속성과 기능을 확장 extends 한다는 의미이다. |
상속을 활용한 멤버십 클래스 구현하기
멤버십 시나리오
회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반 고객(Customer)과 이보다 충성도가 높은 우수 고객(VIPCustomer)에 따른 서비스를 제공하고자 한다. 물품을 구매할 때 적용되는 할인율과 적립되는 포인트 비율이 다르다. 여러 멤버십에 대한 다양한 서비스를 각각 제공할 수 있다. 멤버십에 대한 구현을 클래스 상속을 활용해 구현하자. |
일반 고객(Customer) 클래스 구현
고객의 속성: 고객 아이디, 고객 이름, 고객 등급, 보너스 포인트, 보너스 포인트 적립 비율 일반 고객의 경우 물품 구매시 1%의 보너스 포인트 적립 |
// 일반 고객
public class Customer {
private int customerID;
private String customerName;
private String customerGrade;
int bonusPoint;
double bonusRatio;
public Customer() {
customerGrade = "SILVER";
bonusRatio = 0.01;
}
public int calcPrice(int price) {
bonusPoint += price * bonusRatio;
return price;
}
public String showCustomerInfo() {
return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.";
}
}
우수 고객(VIPCustomer) 구현
매출에 더 많은 기여를 하는 단골 고객 제품을 살 때 10%을 할인해 준다. 보너스 포인트는 제품 가격의 5%를 적립해 준다. 담당 전문 상담원이 배정된다. |
Customer 클래스에 추가해서 구현하는 것은 좋지 않다. VIPCustomer 클래스를 따로 구현한다. 이미 Customer에 구현된 내용이 중복되므로 Customer를 확장해 구현한다. (상속) |
protected 접근 제어자
상위 클래스에 선언된 private 멤버 변수는 하위 클래스에 접근 할 수 없다. 외부 클래스는 접근할 수 없지만, 하위 클래스는 접근 할 수 있도록 protected 접근 제어자를 사용한다. |
public class Customer {
protected int customerID;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
}
Customer와 VIPCustomer 테스트 하기
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());
}
}
// 결과 값
이순신님의 등급은 SILVER이며, 보너스 포인트는 1000입니다.
김유신님의 등급은 VIP이며, 보너스 포인트는 10000입니다.
상속에서 클래스 생성 과정과 형 변환
하위 클래스가 생성 되는 과정
하위 클래스를 생성하면 상위 클래스가 먼저 생성 된다. new VIPCustomer()를 호출하면 Customer()가 먼저 호출 된다. 클래스가 상속 받은 경우 하위 클래스의 생성자에서는 반드시 상위 클래스의 생성자를 호출한다. |
'Java > 패스트캠퍼스' 카테고리의 다른 글
싱글톤 패턴 (0) | 2022.05.30 |
---|---|
static 변수, static 메소드 (0) | 2022.05.30 |
패스트캠퍼스 자바 알고리즘 문제 (0) | 2022.05.17 |
패스트캠퍼스 객체지향 프로그래밍 (0) | 2022.03.18 |
패스트캠퍼스 자바 프로그래밍 (0) | 2022.03.17 |