JAVA / 객체 간의 상속

아몬드봉봉·2023년 12월 12일
0

Java

목록 보기
14/17

상속

  • 상속이란 기존 클래스의 변수와 메서드를 물려받아 새로운 클래스(더 나은, 더 구체적인 클래스)를 구성하는 것을 의미함.
  • 이러한 상속은 캡슐화, 추상화, 다형성과 더불어 객체지향 프로그래밍을 구성하는 특징 중 하나.
  • 예시로 현실세계에서 부모의 생물학적 특성을 자식이 물려받는 유전과 비슷하다 볼 수 있다.
장점
  • 기존 클래스의 변수와 코드를 재사용할 수 있어 개발 시간이 단축된다.
  • 먼저 작성된 검증된 프로그램을 재사용하기 때문에 신뢰성 있는 프로그램을 개발할 수 있다.
  • 클래스 간 계층적 분류 및 관리가 가능하여 유지보수가 용이하다.
단점
  • 자바에서는 클래스의 다중 상속을 지원하지 않는다.
  • 자바에서는 상속의 횟수에 제한을 두지 않는다.
  • 자바에서는 계층구조의 최상위에 java.lang.Object 클래스가 있다.

클래스 상속

  • 새로운 클래스를 정의할 때 이미 구현된 클래스를 상속(inheritance) 받아서 속성이나 기능을 확장하여 클래스를 구현함
  • 이미 구현된 클래스보다 더 구체적인 이능을 가진 클래스를 구현해야 할 때 기존 클래스를 상속함
  • 상속하는 클래스 : 상위 클래스, parent class, base class, super class
  • 상속받는 클래스 : 하위 클래스, child class, derived class, sub class
상속 구현
  • 상위 클래스는 하위 클래스 보다 더 일반적인 개념과 기능을 가짐
  • 하위 클래스는 상위 클래스 보다 더 구체적인 개념과 기능을 가짐
  • 하위 클래스가 상위 클래스의 속성과 기능을 확장(extends) 한다는 의미
상속 선언
  • 상속을 선언할 때는 extends 키워드를 사용한다.
  • extends 키워드 뒤에는 단 하나의 클래스만 올 수 있음
  • public class Human extends Mammal {}

상속 예제

회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반 고객(customer)과 이보다 충성도가 높은 우수고객(VIPCustomer)에 따른 서비스를 제공하고자 함
물품을 구매 할때 적용되는 할인율과 적용되는 보너스 포인트와 비율이 다름
여러 맴버십에 대한 각각 다양한 서비스를 제공할 수 있음
멤버십에 대한 구현을 클래스 상속을 활용하여 구현해보기

일반 고객
  • 고객의 속성 : 고객 아이디, 고객 이름, 고객 등급, 보너스 포인트, 보너스 포인트 적합 비율
  • 일반 고객의 경우 물품 구매 시 1%의 보너스 포인트 적립
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;
    }
    
    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;
    }
 
    public String showCustomerInfo() {
        return customerName + "님의 등급은" + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.";
    }
    
}

protected 접근 제어자

  • 외부 클래스는 접근할 수 없지만, 하위 클래스는 접근할 수 있도록 protected 접근 제어자를 사용
  • protected 멤버는 부모 클래스에 대해서는 public 멤버처럼 취급되며, 외부에서는 private 멤버처럼 취급
  • 접근할 수 있는 영역
    • 이 멤버를 선언한 클래스의 멤버
    • 이 멤버를 선언한 클래스가 속한 패키지의 멤버
    • 이 멤버를 선언한 클래스를 상속받은 자식 클래스(child class)의 멤버
우수 고객
  • Customer 클래스에 추가해서 구현하는 것은 좋지 않음
  • VIPCustomer 클래스를 따로 구현
  • 이미 Customer에 구현된 내용이 중복되므로 Customer를 확장하여 구현함(상속)
public class VIPCustomer extends Customer{
    
    private String agentId;
    double saleRatio;
    
    public VIPCustomer() {
        bonusRatio = 0.05;
        saleRatio = 0.1;
        customerGrade = "VIP";
    }
 
    public String getAgentId() {
        return agentId;
    }
 
}
일반 고객 우수고객 테스트
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입니다.

출처

https://danmilife.tistory.com/21
http://www.tcpschool.com/java/java_modifier_accessModifier

profile
성장을 즐기는 백엔드 자바 개발자

0개의 댓글

관련 채용 정보