C# 강좌 : 제 38강 - 추상
추상(Abstract)
추상(Abstract)
은 여러 파생 클래스에서 상속 받는 객체들을 표준화합니다.
추상 클래스
는 선언만 존재하며 내용은 구현하지 않습니다. 스스로 객체를 생성할 수 없습니다.
상속 받는 경우, 추상 메서드
를 반드시 구현해야합니다. 파생 클래스에서 기본적으로 공유할 수 있는 공통적인 정의를 생성하여 표준화합니다.
전체 코드
using System;
public abstract class Shape
{
public int X, Y;
public abstract double Area();
}
public class Rect : Shape
{
private int Width, Height;
public Rect(int x, int y, int width, int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public override double Area()
{
double area = (Width + Height) / 2;
return area;
}
}
public class Circle : Shape
{
private int Radius;
public Circle(int x, int y, int radius)
{
X = x;
Y = y;
Radius = radius;
}
public override double Area()
{
double area = (Radius * Radius) * 3.14;
return area;
}
}
추상 클래스는 abstract
키워드를 사용하여 정의합니다.
추상 메서드는 선언만 존재하며 중괄호 ({})
를 사용해 메서드를 구현하지 않습니다
파생 클래스는 추상 메서드를 반드시 구현해야하며, override
키워드를 이용해 메서드를 구현합니다
세부 코드
Rect rect = new Rect(100, 100, 50, 50);
Console.WriteLine(rect.Area());
Circle circle = new Circle(100, 100, 50);
Console.WriteLine(circle.Area());
Rect
와 Circle
클래스의 Area
메서드를 실행할 경우, 면적이 계산되어 출력됩니다.
공유하기


댓글 남기기