본문 바로가기

자바 기초

자바 상속 - Do it! 자바프로그래밍 기초

객체 지향 프로그래밍의 중요한 특징 중 하나가 상속이다.

B클래스가 A클래스를 상속받으면 B클래스는 A클래스의 멤버 변수와 메서드를 사용할 수 있고, 

상속을 사용해서 프로그램을 구현하면 유지보수가 편하고 프로그램을 수정하거나 새로운 내용을 추가하는 것이 유연하다는 장점이 있다.

 

상속 하는 클래스를 상위클래스, 상속 받는 클래스를 하위클래스라고 하고,

문법으로 상속을 구현할 때는 extends 예약어를 사용한다.

class B extends A { } 이면 'B클래스가 A클래스를 상속받는다'라고 말한다.

 

package inheritance;

public class Customer {
	protected int customerID; // private는 하위클래스에서도 쓰지못함. protected는 외부 클래스에서는 사용 못하지만 하위클래스에서는 사용가능하도록 함.
	protected String customerName;
	protected String customerGrade;
	int bonusPoint;
	double bonusRatio;
	
	public Customer(int customerID, String customerName)
	{
		this.customerID = customerID;
		this.customerName = customerName;
		customerGrade = "SILVER";
		bonusRatio = 0.01;
	}																						
	public int calcPrice(int price)
	{
		bonusPoint += price * bonusRatio;
		return price;
	}
	
	public String showCustomerInfo()
	{
		return customerName + " 님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "입니다.";
	}
	
	public int getCustomerID() {
		return customerID;
	}

	public void setCustomerID(int cutomerID) {
		this.customerID = cutomerID;
	}

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

public class VIPCustomer extends Customer {
	private int agentID;
	double saleRatio;
	
	public VIPCustomer(int customerID, String customerName, int agentID) 
	{
		customerGrade = "VIP";
		bonusRatio = 0.05;
		saleRatio = 0.1;
		this.agentID = agentID;
	}
	
	public int getAgentID()
	{
		return agentID;
	}
	public String showVIPInfo()
	{
		return super.showCustomerInfo() + "담당 상담원 아이디는 " + agentID + "입니다.";
	}
	
	public int calcPrice(int price)
	{
		bonusPoint += price * bonusRatio;
		return price - (int)(price*saleRatio);
	}
}

VIP 고객은 여러가지 다른 혜택들이 있는데, Customer 클래스에 VIP 고객에게 필요한 변수와 메서드까지 함께 포함하여 구현한다면 Customer 클래스의 코드가 복잡해진다. 그리고 일반 고객의 인스턴스를 생성할 때는 VIP 고객과 관련된 기능은 필요 없는데 VIP 고객의 내용까지 같이 생성되어 낭비가 발생한다.

 

VIP 고객은 일반 고객의 혜택 또한 같이 받기 때문에 Customer 클래스와 겹치는 멤버변수와 메서드가 존재한다. 그렇기 때문에 Customer 클래스를 상속받고, VIPCustomer에만 필요한 agentID와 saleRatio를 선언해줬다.

그리고 이름이 같은 메서드 calcPrice()가 있고, 추가적인 메서드들이 있다. 

이렇게 구현하면 VIPCustomer 클래스는 Customer클래스의 멤버 변수와 메서드를 사용할 수 있고,

추가로 VIPCustomer에서 선언한 멤버변수와 메서드까지 사용이 가능하다.

 

Customer 클래스에서 customerID, customerName, customerGrade 는 protected 예약어로 선언되었는데,

protected 예약어는 외부에서는 사용할 수 없지만, 하위클래스에서는 사용할 수 있도록 지정하는 예약어다. 

상속받은 하위클래스에서는 public처럼 사용할 수 있게 되고, 외부 클래스에서는 private과 동일한 역할을 한다.

만약 customerGrade가 private으로 선언되었다면 VIPCustomer 클래스에서 생성자에 오류가 날 것이다.

 

VIPCustomer 클래스에 이름이 같은 메서드 calcPrice()가 있는데,

하위 클래스에서 메서드를 재정의하는 메서드 오버라이딩으로 관련 설명은 후에 더 게시글을 더 올릴 것이다.