[TIL] 25.01.05 SUN

GDORI·2025년 1월 5일
0

TIL

목록 보기
153/184
post-thumbnail

C# 클래스와 객체

  1. 클래스란?

    • 클래스는 객체를 정의하는 청사진(템플릿)

    • 데이터와 메서드를 하나의 단위로 묶어줌

    • 클래스는 속성, 필드, 메서드, 이벤트 등으로 구성

    • 선언 예시:

      public class Car
      {
          public string Make { get; set; }
          public string Model { get; set; }
      
          public void Drive()
          {
              Console.WriteLine("Driving the car!");
          }
      }
  2. 객체란?

    • 객체는 클래스를 기반으로 생성된 인스턴스
    • 클래스의 속성과 메서드를 사용
    • 객체 생성 예시:
      Car myCar = new Car();
      myCar.Make = "Toyota";
      myCar.Model = "Corolla";
      myCar.Drive();

상속

  1. 정의

    • 상속은 기존 클래스(부모 클래스)의 기능을 다른 클래스(자식 클래스)가 물려받는 것
    • 코드 재사용성을 높이고 확장성을 제공
    • 부모 클래스의 필드와 메서드를 자식 클래스에서 사용할 수 있으며, 필요하면 재정의 가능
  2. 사용 예시

    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();   // 자식 클래스의 메서드

다형성

  1. 정의

    • 다형성은 동일한 인터페이스나 부모 클래스를 공유하는 객체들이 서로 다른 방식으로 동작할 수 있게 하는 특징
    • 메서드 오버라이딩과 인터페이스 구현을 통해 구성
  2. 예시: 메서드 오버라이딩

    • 부모 클래스의 메서드를 자식 클래스에서 재정의
    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
  3. 예시: 인터페이스 구현

    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
profile
하루 최소 1시간이라도 공부하자..

0개의 댓글

관련 채용 정보