C# 상속받아 원과 사각형 넓이 구하기
Shape라는 추상 클래스를 정의하고, 이를 상속받는 Circle, Rectangle 등의 클래스를 만들어 넓이를 계산하는 메서드를 구현하세요. Shape는 추상 메소드 Area()를 가져야합니다.
using UnityEngine;
public abstract class Shape
{
public abstract float Area();
}
public class Circle : Shape
{
float radius;
public Circle(float radius)
{
this.radius = radius;
}
public override float Area()
{
return radius * radius * Mathf.PI;
}
}
public class Rectangle : Shape
{
float width;
float height;
public Rectangle(float width, float height)
{
this.width = width;
this.height = height;
}
public override float Area()
{
return width * height;
}
}
public class Day3 : MonoBehaviour
{
void Start()
{
Circle circle = new Circle(10);
Debug.Log(circle.Area());
Rectangle rect = new Rectangle(5, 20);
Debug.Log(rect.Area());
}
}
추상 클래스인 abstract로 Shape 클래스를 만들어주고, Area()을 선언해준다.
Circle클래스와 Rectangle 클래스는 Shape 클래스를 상속받고, 각각 넓이 구하는 식을 적어준다.
Area()함수는 둘 다 override해서 어떤 클래스에서 부르냐에 따라 겹치지 않도록 구현해준다.