메서드의 다형성
- 오버라이딩 : 같은 이름의 메서드 -> 하위 클래스의 메서드로 수행
- 오버로딩 : 같은 이름의 메서드 -> 자료형의 타입과 개수에 따라 지정된 메서드로 수행
클래스의 다형성
- 업캐스팅 : 상위 클래스의 자료형 참조 변수 -> 여러 하위 클래스의 인스턴스를 참조
AnimalTest.java
package ch06; import java.util.ArrayList; class Animal { public void move() { System.out.println("동물이 움직 입니다."); } } class Human extends Animal { @Override public void move() { System.out.println("사람이 두 발로 걷습니다."); } public void readBook() { System.out.println("사람이 책을 읽습니다."); } } class Tiger extends Animal { @Override public void move() { System.out.println("호랑이가 네 발로 뜁니다."); } public void hunting() { System.out.println("호랑이가 사냥을 합니다."); } } class Eagle extends Animal { @Override public void move() { System.out.println("독수리가 하늘을 날아 다닙니다."); } public void flying() { System.out.println("독수리가 양 날개를 쭉 펴고 날아 다닙니다."); } } public class AnimalTest { public static void main(String[] args) { Animal hAnimal = new Human(); Animal tAnimal = new Tiger(); Animal eAnimal = new Eagle(); AnimalTest test = new AnimalTest(); test.moveAnimal(hAnimal); test.moveAnimal(tAnimal); test.moveAnimal(eAnimal); public void moveAnimal (Animal animal) { animal.move(); // 매개변수 animal의 move 메서드를 실행한다. } } }public class AnimalTest { public static void main(String[] args) { Animal hAnimal = new Human(); Animal tAnimal = new Tiger(); Animal eAnimal = new Eagle(); ArrayList<Animal> animalList = new ArrayList<>(); animalList.add(hAnimal); animalList.add(tAnimal); animalList.add(eAnimal); for(Animal animal : animalList) { animal.move(); } } }출력 결과
- 이처럼 다형성을 사용하면
move()메서드를 실행시키는 하나의 동작으로 여러가지의 출력 결과를 나타낼 수 있습니다.
다형성의 특징
- 유연하고 확장성있게 유지보수가 편리한 프로그램을 만들수 있습니다.
- 다형성을 사용하면 여러 클래스를 하나의 타입(상위 클래스)으로 핸들링 할 수 있습니다.
- 코드의 중복성을 낮추고 가독성을 높일 수가 있습니다.
- 다른 동물을 추가하는 경우 상속과 메서드 재정의를 활용하여 확장성 있는 프로그램을 만들 수 있다.
- 만약 다형성을 사용하지 않으면 많은
if-elseelse if문이 구현되고 코드의 유지보수가 어려워진다.
- 상위 클래스에서는 공통적인 부분을 제공하고 하위 클래스에서는 각 클래스에 맞는 기능을 구현합니다.
- 여러 클래스를 하나의 타입(상위 클래스)으로 핸들링 할 수 있습니다.
SILVER고객과VIP고객 중간GOLD고객 만들기
- 고객이 늘어
SILVER고객보다는 많이 구매하고VIP보다는 적게 구매하는 고객에게도 해택을 주기로 했다.GOLD고객 등급을 만들고 혜택은 다음과 같다.- 제품을 살때는
10%할인해준다.- 보너스 포인트는
2%적립해준다.
Customer.java
package ch06; public class Customer { protected int customerID; protected String customerName; protected String customerGrade; int bounusPoint; double bounusRatio; public Customer(int customerID, String customerName) { customerGrade = "SILVER"; bounusRatio = 0.01; this.customerID = customerID; this.customerName = customerName; } 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 int calcPrice(int price) { bounusPoint += price * bounusRatio; // 보너스 포인트 적립 return price; } public String showCustomerInfo() { return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bounusPoint + "입니다."; } }
GoldCustomer.java
package ch06; public class GoldCustomer extends Customer { double salesRatio; public GoldCustomer(int customerID, String customerName) { super(customerID, customerName); customerGrade = "GOLD"; salesRatio = 0.1; bounusRatio = 0.02; } public int calcPrice(int price) { bounusPoint += price * bounusRatio; // 보너스 포인트 2% 적립 return price - (int) (price * salesRatio); // 상품가 10% 할인 } }
VIPCustomer.java
package ch06; public class VIPCustomer extends Customer { int salesPrice; double salesRatio; private String agentID; public VIPCustomer(int customerID, String customerName) { super(customerID, customerName); customerGrade = "VIP"; bounusRatio = 0.05; salesRatio = 0.1; } public String getAgent() { return agentID; } @Override // calcPrice 메서드 재정의 public int calcPrice(int price) { bounusPoint += price * bounusRatio; price -= price * salesRatio; // 상품 가격 - 할인가 return price; } }
CustomerTest.java
package ch06; import java.util.ArrayList; public class CustomerTest { public static void main(String[] args) { ArrayList<Customer> customerList = new ArrayList<>(); Customer customerT = new Customer(10010, "Tomas"); Customer customerJ = new Customer(10020, "James"); Customer customerE = new GoldCustomer(10030, "Edward"); Customer customerP = new GoldCustomer(10040, "Percy"); Customer customerK = new VIPCustomer(10050, "Kim"); customerList.add(customerT); customerList.add(customerJ); customerList.add(customerE); customerList.add(customerP); customerList.add(customerK); System.out.println("====== 고객 정보 출력 ======="); for(Customer customer : customerList) { System.out.println(customer.showCustomerInfo()); } System.out.println(); 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.getCustomerName() + "님의 현재 보너스 포인트는 " + customer.bounusPoint + "입니다."); } } }출력 결과
SILVER고객에게1%포인트 적립Gold고객에게2%포인트 적립과 상품가10%할인VIP고객에게5%포인트 적립과 상품가10%할인