C# 강좌 : 제 37강 - 다형성
다형성(Polymorphism)
다형성은 부모 클래스의 멤버
를 재정의하거나 메서드
를 재정의하지 않고 상속할 때 사용합니다.
자식 클래스에서 재정의 하려면 부모 클래스에서 virtual
또는 abstract
로 선언된 경우에만 재정의할 수 있습니다.
자식 클래스에서는 override
키워드를 통하여 오버라이드(Override)
를 할 수 있습니다.
전체 코드
using System;
class Shape
{
public int X, Y = 0;
protected int Width, Height = 0;
public Shape(int x, int y)
{
X = x;
Y = y;
Width = x + 100;
Height = y + 100;
}
public virtual int Area()
{
return Width * Height;
}
}
class Rect : Shape
{
public Rect(int x, int y) : base(x, y)
{
Height = y + 50;
}
public override string ToString()
{
return String.Format("{0}, {1}, {2}, {3}", X, Y, Width, Height);
}
}
class Circle : Shape
{
private int Radius;
public Circle(int x, int y) : base(x, y)
{
Radius = (x + y) / 4;
}
public override int Area()
{
return (int)(Radius * Radius * 3.14);
}
public override string ToString()
{
return String.Format("{0}, {1}, {2}", X, Y, Radius);
}
}
부모 클래스에서 생성된 Area
메서드를 virtual
로 선언하여 자식 클래스에서 수정이 가능하게끔 선언합니다.
자식 클래스인 Rect
는 ToString()
메서드를 상속받아 변형합니다.
ToString()
메서드는 기본적으로 지원되는 메서드이므로, 상속할 수 있습니다.
자식 클래스인 Circle
은 Area
메서드를 상속받아 반환 값을 변형합니다.
세부 코드
Rect rect = new Rect(100, 100);
Console.WriteLine(rect.Area());
Console.WriteLine(rect.ToString());
Circle circle = new Circle(100, 100);
Console.WriteLine(circle.Area());
Console.WriteLine(circle.ToString());
Rect
와 Circle
클래스의 Area
메서드를 실행할 경우, 면적이 계산되어 출력됩니다.
Rect
와 Circle
클래스의 ToString
메서드를 실행할 경우, 클래스의 멤버들이 출력됩니다.
공유하기


댓글 남기기