25강. 다형성 활용과 다운캐스팅(4)

철새·2022년 3월 1일
0
  • Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
  • Section 1. 자바의 핵심 - 객체지향 프로그래밍
  • 25강 "다형성 활용과 다운캐스팅(4)"
  • 다형성 활용하기 > 상속은 언제 사용할까? > 다운 캐스팅 - instanceof

지난 강의에서 다형성을 활용해보기 위해 GoldCustomer 클래스를 만들어주었다.
이번 시간에는 교재에 있는 내용대로 만들어보겠다.

다형성 활용하기

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

	public int getAgentID() {
		return agentID;
	}
}
public class GoldCustomer extends Customer{
	private double saleRatio;
	
	public GoldCustomer(int customerID, String customerName) {
		super(customerID, customerName);
		customerGrade = "Gold";
		bonusRatio = 0.02;
		saleRatio = 0.1;
	}

	@Override
	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price - (int)(price*saleRatio);
	}
}
import java.util.ArrayList;

public class CustomerTest {
	public static void main(String[] args) {
		ArrayList<Customer> customerList = new ArrayList<Customer>();
		
		Customer customerLee = new Customer(10010, "이순신");
		Customer customerShin= new Customer(10011, "신사임당");
		GoldCustomer customerHong = new GoldCustomer(10012, "홍길동");
		GoldCustomer customerYul = new GoldCustomer(10013, "율곡");
		VIPCustomer customerKim = new VIPCustomer(10014, "김유신", 100);
		
		customerList.add(customerLee);
		customerList.add(customerShin);
		customerList.add(customerHong);
		customerList.add(customerYul);
		customerList.add(customerKim);
		
		System.out.println("============= 고객정보 출력 ==============");
		for(Customer customer : customerList) {
			System.out.println(customer.showCustomerInfo());
		}
		
		System.out.println("========== 할인율과 보너스 포인트 결과 ===========");
		int price = 10000;
		for(Customer customer : customerList) {
			int cost = customer.calcPrice(price);
			System.out.println(customer.getCustomerName() + "님이 " + cost + "원을 지불하셨습니다.");
			System.out.println(customer.showCustomerInfo());
		}
	}
}

상속은 언제 사용할까?

  • 여러 클래스를 생성하지 않고 하나의 클래스에 공통적인 요소를 모으고 나머지 클래스는 이를 상속받은 다음 각각 필요한 특성과 메서드를 구현하는 방법을 사용한다.
  • 하나의 클래스에 여러 특성을 한꺼번에 구현하는 경우 많은 코드 내에 많은 if문이 생길 수 있다.
  • IS-A 관계 (is a relatioship : inheritance)
    일반적인(general) 개념과 구체적인(specific) 개념과의 관계
    상위 클래스 : 일반적인 개념 클래스 (예 : 포유류)
    하위 클래스 : 구체적인 개념 클래스 (예 : 사람, 원숭이, 고래...)
    단순히 코드를 재사용하는 목적으로 사용하지 않음
  • HAS-A 관계(composition)
    한 클래스가 다른 클래스를 소유한 관계
    코드 재사용의 한 방법으로, 클래스 안에서 다른 클래스를 객체로 생성하는 경우를 말함
// HAS-A 관계
class Student {
	Subject majorSubject;
}

다운 캐스팅 - instanceof

  • 하위 클래스가 상위 클래스로 형변환되는 것은 묵시적으로 이루어진다.
  • 다시 원래 자료형인 하위 클래스로 형변환 하려면 명시적으로 다운 캐스팅을 해야한다.
  • 이 때, 원래 인스턴스의 타입을 체크하는 예약어가 instanceof 이다.

지난 강의에서 다형성 예제에 사용한 Animal 클래스이다.
Human, Tiger, Eagle 클래스에 각각 고유의 메서드를 추가하고,
Test 클래스의 메서드에서 다운캐스팅을 활용해 해당 메서드를 호출하는 코드이다.

class Animal{
	public void move() {
		System.out.println("동물이 움직입니다.");
	}
}
class Human extends Animal{
	public void move() {
		System.out.println("사람이 두발로 걷습니다.");
	}
	public void readBook() {
		System.out.println("사람이 책을 읽습니다.");
	}
}
class Tiger extends Animal{
	public void move() {
		System.out.println("호랑이가 네발로 뜁니다.");
	}
	public void hunting() {
		System.out.println("호랑이가 사냥을 합니다.");
	}
}
class Eagle extends Animal{
	public void move() {
		System.out.println("독수리가 하늘을 납니다.");
	}
	public void flying() {
		System.out.println("독수리가 하늘을 납니다.");
	}
}

public class AnimalTest {
	public static void main(String[] args) {
		AnimalTest test = new AnimalTest();
		test.moveAnimal(new Human());
		test.moveAnimal(new Tiger());
		test.moveAnimal(new Eagle());
	}
	public void moveAnimal(Animal animal) {
		animal.move();
		if(animal instanceof Human) {
			Human human = (Human)animal;
			human.readBook();
		}else if(animal instanceof Tiger) {
			Tiger tiger = (Tiger)animal;
			tiger.hunting();
		}else if(animal instanceof Eagle) {
			Eagle eagle = (Eagle)animal;
			eagle.flying();
		}else {
			System.out.println("지원되지 않는 기능입니다.");
		}
	}
}

profile
효율성을 추구하며 세상을 떠도는 철새입니다.

0개의 댓글

관련 채용 정보