☕ 자바 JAVA/☕ 클래스와 함수 Class & Method

[JAVA]다형성의 장점1:매개변수의 다형성

yeun.log 2024. 4. 7. 04:34
반응형

 

참조형 매개변수는 method 호출 시,
자신과 같은 type 또는 자손type의 instance를 넘겨줄 수 있다.

 

걍 아래 예제 보시는 게 이해가 빠름

 

제품을 구매할 때 계산하는 코드를 짜려면

 

이렇게 제품마다 method를 만들게 아니라

 

이렇게 제품들의 조상 class인 Product로 다 쓸 수있어 편하다.

 


 

이거 보고 정리하는 거라고 전에 적긴 했는데

https://youtu.be/U-VGYYH-obM?si=1EFn4V2pSL45XxRi

 

간단한 코드지만 정말 깔끔하고 좋네요^^

 

public class ParameterPolymorphism {

    public static void main(String[] args) {
        Buyer b = new Buyer();

        b.buy(new Tv());
        b.buy(new Computer());  // buy(Product p)

        System.out.println("현재 남은 돈은 " + b.money + "만원입니다.");
        System.out.println("현재 보너스점수는 " + b.bonusPoint + "점입니다.");
    }
}

class Product {
    int price;      // 제품가격
    int bonusPoint; // 포인트점수

    Product(int price) {
        this.price = price;
        bonusPoint = (int)(price/10.0);   // 제품가격의 10%가 bonusPoint
    }
}
class Tv extends Product {
    Tv() {
        super(200);
    }
    public String toString() {  return "Tv";    }
}
class Computer extends Product {
    Computer() {
        super(300);
    }

    public String toString() {  return "Computer";  }
}
class Audio extends Product {
    Audio() {
        super(100);
    }

    public String toString() {  return "Audio"; }
}
class Buyer {
    int money = 1000;
    int bonusPoint = 0;

    void buy(Product p) {
        if (money < p.price) {
            System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
            return;
        }

        money -= p.price;
        bonusPoint += p.bonusPoint;
        System.out.println(p + "을/를 구입하셨습니다.");
    }
}
  1. main에서 Buyer class 호출
  2. Buyer의 buy 함수를 사용하는데 이때 parameter로 new instance를 사용하면서 객체생성
  3. 자손 class인 Tv, Computer, Audio class들은 조상인 Productc class에 super(가격)을 보냄
  4. Buyer에서 Product class의 money와 bonusPoint를 받아 마무리 함

출력결과

 

반응형