추상 클래스에는 파생 클래스에 의해 구현되는 추상 메서드가 포함됩니다. 파생 클래스에는 보다 전문화된 기능이 있습니다.
다음은 C#에서 추상 클래스의 사용을 보여주는 예입니다.
예시
using System;
namespace Demo {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
Console.WriteLine("Length of Rectangle: "+length);
Console.WriteLine("Width of Rectangle: "+width);
}
public override int area () {
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(14, 8);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
} 출력
Length of Rectangle: 14 Width of Rectangle: 8 Area: 112
위의 추상 클래스는 -
abstract class Shape {
public abstract int area();
} 다음은 추상 클래스에 대한 규칙입니다.
- 추상 클래스의 인스턴스를 만들 수 없습니다.
- 추상 클래스 외부에서 추상 메소드를 선언할 수 없습니다.
- 클래스가 봉인된 것으로 선언되면 상속될 수 없으며 추상 클래스는 봉인된 것으로 선언될 수 없습니다.