Do it 자바 프로그래밍 입문 [상속과 다형성(1)]

wish17·2022년 11월 2일
0

Do it 자바

목록 보기
8/10

상속과 다형성(1)

상속이란? (1)

  • 클래스를 정의할 때 이미 구현된 클래스를 상속(ingeritance) 받아서 속성이나 기능이 확장되는 클래스를 구현한다.
  • 상속하는 클래스 : 상위 클래스, parent class, base class, super class
  • 상속 받는 클래스 : 하위 클래스, child class, derived class, subclass

  • 클래스 상속 문법
class B extends A{
	code...
}

상속이란? (2)

  • 상위 클래스는 하위 클래스보다 일반적인 의미를 가진다.
  • 하위 클래스는 상위 클래스보다 구체적인 의미를 가진다.

extends 뒤에는 단 하나의 class만 사용할 수 있다. (자바는 single inheritance만 지원함)

public class Piont{
	private int x;
    private int y;
    public int getX(){
    	return x;
    }
    public void setX(int x){
    	this.x = x;
    }
    public int getY(){
    	return x;
    }
    public void setY(int y){
    	this.y = y;
    }
}

x와 y 값을 갖는 Point라는 클래스가 있다고 하자.
이 때, 중심(점)과 반지름을 갖는 Circle 클래스를 만든다면 Circle 클래스는 Point 클래스를 상속받는 것이 아니라 객체를 생성해서 변수에 넣어주면 된다.

잘못된 코드 예시

public class Circle extends Point{
    private int radius;
}

권장되는 코드 예시

public class Circle {
	Point point;
    private int radius;
    
    public Circle(){
    	point = new Point();
    }
}

Point 클래스가 일반적이고, Circle 클래스가 구체적인 관계가 아니기 때문에 상속 관계가 아닌 것이다. (따라서 위 경우에는 extends로 상속해서 point를 사용하는게 아니라 객체를 생성해서 변수에 넣어 사용 한다.)

상속을 활용한 고객관리 프로그램

  • 고객의 정보를 활용하여 고객 맞춤 서비스를 구현
  • 고객의 등급에 따라 차별화된 할인율과 포인트를 지급
  • 등급에 따른 클래스를 따로 구현하는 것이 아닌 일반적인 클래스를 먼저 구현하고, 그보다 기능이 많은 클래스는 상속을 활용하여 구현

Customer 클래스 속성

멤버 변수설명
customerID고객 아이디
customerName고객 이름
customerGrade고객 등급
(기본 생성자에서 지정되는 기본 등급은 SILVER)
bonusPoint고객의 보너스 포인트
(고객이 제품을 구매할 경우 누적되는 보너스 포인트)
bonusRatio보너스 포인트 적립 비율
(고객이 제품을 구매할 때 보너스 포인트로 적립될 적립 비율)
(기본 생성자에서 지정되는 적립 비율은 1%)

Customer 클래스

public class Customer {
	
	protected int customerID; // protected = 상속 관계에서만 public으로 보이게 해주는 기능
	protected String customerName;
	protected String customerGrade;
	int bonusPoint;
	protected double bonusRatio;
	
	public Customer() {
		customerGrade = "SILVER";
		bonusRatio = 0.01;
	}
	
	public int calcPrice(int price) {
		bonusPoint += price * bonusPoint;
		return price;
	}
	public void showCustomerInfo() {
		System.out.println(customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.");
	}

	public int getCustomerID() {
		return customerID;
	}
	public int getBonusPoint() {
		return bonusPoint;
	}

	public void setBonusPoint(int bonusPoint) {
		this.bonusPoint = bonusPoint;
	}

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

protected
= 상속 관계에서만 public으로 보이게 해주는 기능

새로운 고객 등급이 필요한 경우

  • 단골 고객에 대한 혜택이 필요함
  • 우수 고객을 관리하기 위해 다음과 같은 혜택을 줌
  • 고객 등급 : VIP
  • 제품 구매 할인율 : 10%
  • 보너스 포인트 : 5%
  • 담당 전문 상담원 배정

VIPCustomer 클래스

public class VIPCustomer extends Customer{
	private int agentID;
	private double saleRatio;
	
	public VIPCustomer() {
		customerGrade = "VIP";
		bonusRatio = 0.05;
		saleRatio = 0.1;
	}
	
	public int getAgentID() {
		return agentID;
	}
}

child class(VIPCustomer class)는 parent class(Customer class)를 그대로 복사해와서 사용하므로 중복되는 변수나 메서드는 다시 선언할 필요가 없다

  • potected 로 변수를 선언하면 상속받는 클래스에서 해당 변수에 접근할 수 있다.
    (다른 패키지에 있어도 접근 가능)
  • public 으로 선언하면 어디서든 접근 가능
  • private 으로 선언하면 해당 클래스 내부에서만 접근 가능
  • 아무런 선언도 하지 않으면 (default) 같은 패키지 내에서 접근 가능

main 클래스

public class CustomerTest1 {
	
	public static void main(String[] args) {
		
		Customer customerLee = new Customer();
		customerLee.setCustomerID(10100);
		customerLee.setCustomerName("Lee");
		
		VIPCustomer customerKim = new VIPCustomer();
		customerKim.setCustomerID(10101);
		customerKim.setCustomerName("Kim");
		
		customerLee.showCustomerInfo();
		customerKim.showCustomerInfo();
		
		
	}

}

0개의 댓글