봄수의 연구실

다형성(Polymorphism) 본문

DEV/Java

다형성(Polymorphism)

berom 2023. 4. 27. 10:03

다형성(Polymorphism)

다형성은 여러 가지 형태를 가질 수 있는 능력을 말합니다.
프로그래밍에서 다형성은 한 인터페이스나 클래스를 사용하여 여러 개의 다른 타입의 객체를 참조하거나 처리할 수 있는 능력을 의미합니다.

다형성을 사용해야 하는 이유는 다음과 같습니다:

  1. 코드의 재사용: 다형성을 사용하면 기존 클래스를 수정하지 않고 새로운 클래스를 추가하여 코드를 재사용할 수 있습니다.
  2. 유연성: 다형성을 사용하면 한 코드 블록에서 여러 타입의 객체를 처리할 수 있습니다
  3. 확장성: 다형성을 사용하면 새로운 타입의 객체를 추가할 때 기존 코드를 수정하지 않고도 프로그램을 확장할 수 있습니다.

Example. Customer

class Customer {
    protected int id;
    protected String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public void getCustomerInfo() {
        System.out.println("ID: " + id + ", Name: " + name);
    }
}

class GoldCustomer extends Customer {
    private int bonusPoints;

    public GoldCustomer(int id, String name, int bonusPoints) {
        super(id, name);
        this.bonusPoints = bonusPoints;
    }

    @Override
    public void getCustomerInfo() {
        super.getCustomerInfo();
        System.out.println("Bonus points: " + bonusPoints);
    }
}

public class Main {
    public static void main(String[] args) {
        Customer customer = new GoldCustomer(1, "Kim", 100);
        customer.getCustomerInfo(); // ID: 1, Name: Kim, Bonus points: 100

        GoldCustomer goldCustomer = new GoldCustomer(2, "Lee", 200);
        goldCustomer.getCustomerInfo(); // ID: 2, Name: Lee, Bonus points: 200
    }
}

이 예시에서 Customer customer = new GoldCustomer(1, "Kim", 100); 코드를 통해 Customer 타입의 변수 customerGoldCustomer 객체를 할당합니다.
변수 customer의 선언 타입은 Customer이지만 실제 객체는 GoldCustomer입니다.

customer.getCustomerInfo();를 호출하면, 실제 객체인 GoldCustomergetCustomerInfo() 메소드가 호출되어 ID, 이름, 그리고 보너스 포인트 정보가 출력됩니다.
이는 다형성을 이용한 예시로, 상속 관계에서 자식 클래스의 객체를 부모 클래스 타입의 변수에 할당할 수 있으며, Overriding(재정의) 된 메소드가 호출됩니다

마치며

다형성을 사용하지 않으면, 여러 조건에 따른 분기를 계속 해야 하고, 많은 if-else문이 필요할 수 있습니다.
이럴 경우, 클래스를 분리하여 코드를 개선할 필요가 있습니다.

부족한 점이나 잘못 된 점을 알려주시면 시정하겠습니다 :>

'DEV > Java' 카테고리의 다른 글

가상 함수(Virtual Method)  (0) 2023.04.27
Is-A와 HAS-A 또는 Inheritance와 Composition - 🐥 카카오 테크 캠퍼스  (0) 2023.04.27
Overriding(재정의)  (0) 2023.04.27
상속(Inheritance)  (0) 2023.04.27
Super 키워드  (0) 2023.04.26