정적 다형성(Static Polymorphism)에서는 함수 호출에 대한 응답이 컴파일 시점에 결정됩니다. 반면 동적 다형성(Dynamic Polymorphism)은 런타임 시점에 결정되는데, 이것이 바로 우리가 말하는 늦은 바인딩(Late Binding), 즉 지연 바인딩입니다.
동적 다형성은 추상 클래스와 가상 함수(virtual function)를 통해 구현됩니다. 어떤 메서드가 호출될지 컴파일러가 미리 확정하지 않고 프로그램 실행 중에 실제 객체의 타입을 기준으로 결정하기 때문에, 코드가 더욱 유연하고 확장 가능해집니다.
동적 다형성 예제
다음 예제는 부모 클래스인 Shape를 상속받은 Rectangle과 Triangle 클래스가 각각 area() 메서드를 재정의(override)하여 서로 다른 결과를 반환하는 모습을 보여줍니다.
using System;
namespace PolymorphismApplication {
class Shape {
protected int width, height;
public Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
public virtual int area() {
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape {
public Rectangle( int a = 0, int b = 0): base(a, b) {}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape {
public Triangle(int a = 0, int b = 0): base(a, b) {}
public override int area() {
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller {
public void CallArea(Shape sh) {
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester {
static void Main(string[] args) {
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}실행 결과
Rectangle class area : Area: 70 Triangle class area : Area: 25
코드 핵심 포인트
- Shape 클래스의 area() 메서드는
virtual키워드로 선언되어 있어 자식 클래스에서 재정의할 수 있습니다. - Rectangle과 Triangle 클래스는 각각
override키워드를 사용해 area()를 자신의 방식대로 구현했습니다. - Caller 클래스의 CallArea() 메서드는 매개변수로 Shape 타입을 받지만, 런타임에 전달된 객체가 Rectangle인지 Triangle인지에 따라 알맞은 area() 메서드가 호출됩니다. 이것이 늦은 바인딩이 작동하는 방식입니다.
결과적으로 같은 CallArea() 메서드를 호출했음에도 Rectangle에서는 넓이 70(10 × 7), Triangle에서는 25(10 × 5 ÷ 2)가 출력되며, 이를 통해 런타임에 메서드 결정이 이루어진다는 것을 확인할 수 있습니다.