객체 지향 언어에서 중요한 개념인 다형성에 대해서 설명해 보겠습니다.
최대한 간단하게 설명하면 1개 인터페이스, 여러 함수로 표현 할 수 있습니다.
우선 중요 개념인 함수 오버로딩에 대해서 간단한 샘플 코드를 보도록 하겠습니다.
1) Function Overloading
using System; namespace PolymorphismApplication { class Printdata { void print(int i) { Console.WriteLine("Printing int: {0}", i ); } void print(double f) { Console.WriteLine("Printing float: {0}" , f); } void print(string s) { Console.WriteLine("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p.print(5); // Call print to print float p.print(500.263); // Call print to print string p.print("Hello C++"); Console.ReadKey(); } } }
Printdata 클래스에 print()라는 이름의 동일한 멤버 함수가 선언되어 있습니다. 사실은 각각 함수이름은 같지만 함수의 파라미터는 각각 다릅니다. print(int i), print(double f), print(string s) 그 후 Printdata 클래스를 객체화 한후 동일한 이름 print를 함수를 호출하면 각 파라미터에 맞는 함수가 호출 됩니다. 이렇게 동작하는 게 함수 오버로딩 입니다.
2) 동적 다형성 (Dynamic Polymorphism)
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
위 코드에서 virtual 키워드를 짚고 넘어 가야 합니다. 즉, 상위 클래스에서 선언되어 있는 것을 자식 클래스에서 재정의를 해서 사용할 수있다는 의미입니다. 즉, Rectangle과 Triangle 각 클래스에 대해서 상위 Shape에 대해서 선언한 virtual 함수를 아래 처럼 재정의 했습니다.
public virtual int area()
<->
public override int area()
실제 함수는 재정의된 함수로 호출 되는 것을 위 샘플 코드를 통해서 알 수 있습니다.
virtual <-> override는 한쌍으로 동작합니다. 기억해 두세요.
'C#(CSharp) > 기초강좌(Basic)' 카테고리의 다른 글
[20] C# 네임스페이스 (C# Namespace) (0) | 2015.02.23 |
---|---|
[19] C# 인터페이스 ( C# interface) (0) | 2015.02.23 |
[17] C# 상속 (C# Inheritance) (0) | 2015.02.23 |
[16] C# 클래스 생성자, 파괴자, 스택틱 (C# class, constructor, destructor, static) (0) | 2015.02.23 |
[15] C# Enum (0) | 2015.02.23 |