Polymorphism

Polymorphism is the provision of a single interface to entities of different types.

Kinds of Polymorphism:

Ad hoc Polymorphism

Ad hoc polymorphism 은 Java 의 overloading 이라고 생각하면 된다.

Parametric Polymorphism

In programming languages and type theory, parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety.

Parametric Polymorphism 은 Java 의 Generic 이라고 생각하면 된다.

Collection<Animal> animals = new ArrayList<Animal>();

Inclusion Polymorphism

Inclusion Polymorphism, also called as Subtyping Inclusion Polymorphism.

참조를 통해 Derived Class(sub class) 를 사용하는 기법이다.

abstract class Image {
    public Image() {
    }
 
    abstract void display();
}
 
class Jpg extends Image {
    public Jpg() {
    }
 
    @Override
    void display() {
        System.out.println("JPG Image File");
    }
}
 
class Png extends Image {
    public Png() {
    }
 
    @Override
    void display() {
        System.out.println("PNG Image File");
    }
}
 
public class Main {
    public static void main(String[] args) {
        Image img;
        Jpg jg = new Jpg();
        Png pg = new Png();
 
        // stores the reference of Jpg
        img = jg;
 
        // invoking display() method of Jpg
        img.display();
 
        // stores the reference of Png
        img = pg;
 
        // invoking display() method of Png
        img.display();
    }
}

Coercion Polymorphism

Coercion Polymorphism, also called as Casting Coercion Polymorphism occurs when an object or primitive is cast into some other type.

User Defined Data type 을 Fundamental Data type 으로 변경하는 것을 의미한다.

class IntClass {
    private int num;
 
    public IntClass(int a) {
        num = a;
    }
 
    public int intValue() {
        return num;
    } // conversion from User-defined type to Basic type
}
 
class Main {
    public static void show(int x) {
        System.out.println(x);
    }
 
    public static void main(String[] args) {
        IntClass i = new IntClass(100);
        show(746);
        show(i.intValue());
    }
}

The Nature of Polymorphism

  • 다형성으로 인터페이스를 구현한 객체를 실행 시점에서 유연하게 변경할 수 있다.
  • 클라이언트를 변경하지 않고 서버 기능을 유연하게 변경할 수 있다.

Spring Framework 에서 Inversion of Control & Dependency Injection 은 다형성을 활용해서 역할과 구현을 편리하게 다룰 수 있도록 해준다. 클라이언트 코드 변경 없이 쉽게 기능 확장이 가능한 이유가 Spring Framework 의 IoC/DI 때문이다.

Dependency Inversion Principle

Dependency Inversion Principle 은 추상화에 의존해야지 구체화에 의존하면 안된다는 원칙이다. 즉, 역할에 의존해야지 구현에 의존하지 말라는 원칙이다.

Polymorphic Types