클래스란?
클래스는 객체를 정의하는 청사진(템플릿)
데이터와 메서드를 하나의 단위로 묶어줌
클래스는 속성, 필드, 메서드, 이벤트 등으로 구성
선언 예시:
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public void Drive()
{
Console.WriteLine("Driving the car!");
}
}
객체란?
Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Model = "Corolla";
myCar.Drive();
정의
사용 예시
public class Vehicle
{
public string Color { get; set; }
public void Start()
{
Console.WriteLine("Vehicle is starting");
}
}
public class Car : Vehicle
{
public int NumberOfDoors { get; set; }
public void Honk()
{
Console.WriteLine("Car is honking");
}
}
Car myCar = new Car();
myCar.Color = "Red";
myCar.Start(); // 부모 클래스의 메서드
myCar.Honk(); // 자식 클래스의 메서드
정의
예시: 메서드 오버라이딩
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Cat meows");
}
}
Animal myAnimal = new Dog();
myAnimal.Speak(); // Output: Dog barks
myAnimal = new Cat();
myAnimal.Speak(); // Output: Cat meows
예시: 인터페이스 구현
public interface IShape
{
void Draw();
}
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
public class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle");
}
}
IShape shape = new Circle();
shape.Draw(); // Output: Drawing a circle
shape = new Rectangle();
shape.Draw(); // Output: Drawing a rectangle