JAVA/Java2021-2

객체 지향 -1. 상속 (단일상속, protected 접근제어자)

RoarinGom 2021. 11. 8. 21:50

자바 언어 추구 : 안정성, 심플

- C나 C++보다 안정적인 언어를 만들자.

(상속받을 수 있는 클래스가 많을 수록 기능의 확장이 가능하지만, 그로 인해 발생할 수 있는 모호성, 문제점을 예방

-> single inheritance)

 

상속을 구현 하는 경우 (결이 같은)

멤버십 시나리오 구현

package Basic_Grammar.chap3_OOP.ch01_inheritance;

public class Customer {
    protected int customerID;
    protected String customerName;
    protected String customerGrade;
    int bonusPoint;
    double bonusRatio;

    public Customer() {
        //생성자 등급 실버, 보너스 비율 10프로
        customerGrade="SILVER";
        bonusRatio=0.01;
    }
    //일반 고객은 보너스 포인트만 추가되도록
    public int calcPrice(int price){
        bonusPoint+=price*bonusRatio;
        return price;
    }

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

}

-> 부모 클래스에서 private 접근제어자를 사용하면 자식(하위)클래스에서도 접근하지 못하기 때문에

protected 접근제어자로 변경하여 하위클래스가 상위클래스의 멤버 변수에 접근할 수 있도록 해준다.

VIP 고객(고객 클래스에서 조건문으로 설정해줄 수는 있으나 클래스 단일성이 망가질 수 있다) 이런 경우 상속을 고려해보자

 

package Basic_Grammar.chap3_OOP.ch01_inheritance;

public class VIPCustomer extends Customer{

    double salesRatio;
    private String agentID;

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

    public String getAgentID() {
        return agentID;
    }

    public void setAgentID(String agentID) {
        this.agentID = agentID;
    }
}
package Basic_Grammar.chap3_OOP.ch01_inheritance;

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());
    }
}