C# Object-Oriented Programming


객체 지향 프로그래밍 (Object-Oriented Programming)

객체 지향 프로그래밍 소개 (Introduction to Object-Oriented Programming)

객체 지향 프로그래밍(OOP)은 데이터를 객체로 묶어 관리하는 프로그래밍 패러다임입니다. 객체는 데이터와 그 데이터를 처리하는 메서드를 포함합니다. C#은 강력한 객체 지향 언어로, OOP의 핵심 개념인 클래스, 객체, 상속, 다형성, 추상화, 캡슐화를 지원합니다.

클래스와 객체 (Classes and Objects)

클래스는 객체를 정의하는 청사진입니다. 객체는 클래스의 인스턴스입니다. 클래스는 속성(데이터)과 메서드(기능)로 구성됩니다.

예제: 클래스 정의 및 객체 생성 (Defining a Class and Creating an Object)

using System;

namespace OOPExample
{
    class Person
    {
        // 속성 (Properties)
        public string Name { get; set; }
        public int Age { get; set; }

        // 메서드 (Methods)
        public void Introduce()
        {
            Console.WriteLine($"안녕하세요, 저는 {Name}이고, 나이는 {Age}입니다.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 객체 생성 (Creating an Object)
            Person person = new Person();
            person.Name = "Alice";
            person.Age = 30;

            // 메서드 호출 (Calling a Method)
            person.Introduce();
        }
    }
}

이 예제에서 Person 클래스는 NameAge 속성을 가지며, Introduce 메서드를 통해 자신을 소개합니다. Person 클래스의 인스턴스인 person 객체를 생성하고 속성을 설정한 후 메서드를 호출합니다.

상속 (Inheritance)

상속은 기존 클래스(부모 클래스)의 속성과 메서드를 새로운 클래스(자식 클래스)가 물려받는 기능입니다. 이를 통해 코드의 재사용성을 높일 수 있습니다.

예제: 상속 (Inheritance)

using System;

namespace OOPExample
{
    // 부모 클래스 (Parent Class)
    class Animal
    {
        public string Name { get; set; }

        public void Eat()
        {
            Console.WriteLine($"{Name} is eating.");
        }
    }

    // 자식 클래스 (Child Class)
    class Dog : Animal
    {
        public void Bark()
        {
            Console.WriteLine($"{Name} is barking.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            dog.Name = "Buddy";
            dog.Eat(); // 부모 클래스의 메서드 호출
            dog.Bark(); // 자식 클래스의 메서드 호출
        }
    }
}

이 예제에서 Dog 클래스는 Animal 클래스를 상속받아 Eat 메서드를 사용할 수 있으며, 자체적으로 Bark 메서드를 추가로 가집니다.

다형성 (Polymorphism)

다형성은 동일한 인터페이스를 통해 다른 실제 구현을 사용하는 기능입니다. 메서드 오버로딩과 오버라이딩을 통해 구현할 수 있습니다.

예제: 메서드 오버라이딩 (Method Overriding)

using System;

namespace OOPExample
{
    class Animal
    {
        public virtual void MakeSound()
        {
            Console.WriteLine("Animal sound");
        }
    }

    class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Bark");
        }
    }

    class Cat : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Meow");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Animal myDog = new Dog();
            Animal myCat = new Cat();

            myDog.MakeSound(); // "Bark" 출력
            myCat.MakeSound(); // "Meow" 출력
        }
    }
}

이 예제에서 DogCat 클래스는 Animal 클래스를 상속받아 MakeSound 메서드를 각각 오버라이딩합니다. 런타임 시점에 객체의 실제 타입에 따라 다른 메서드가 호출됩니다.

추상화 (Abstraction)

추상화는 중요한 정보만 노출하고 불필요한 세부 사항은 숨기는 개념입니다. 추상 클래스와 인터페이스를 통해 구현할 수 있습니다.

예제: 추상 클래스 (Abstract Class)

using System;

namespace OOPExample
{
    abstract class Shape
    {
        public abstract double GetArea();
    }

    class Circle : Shape
    {
        public double Radius { get; set; }

        public Circle(double radius)
        {
            Radius = radius;
        }

        public override double GetArea()
        {
            return Math.PI * Radius * Radius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Shape circle = new Circle(5);
            Console.WriteLine($"Area of the circle: {circle.GetArea()}");
        }
    }
}

이 예제에서 Shape는 추상 클래스이며, GetArea 추상 메서드를 정의합니다. Circle 클래스는 Shape를 상속받아 GetArea 메서드를 구현합니다.

캡슐화 (Encapsulation)

캡슐화는 데이터와 메서드를 하나로 묶고, 데이터의 접근을 제한하는 개념입니다. 접근 제한자를 통해 구현할 수 있습니다.

예제: 캡슐화 (Encapsulation)

using System;

namespace OOPExample
{
    class BankAccount
    {
        private double balance;

        public void Deposit(double amount)
        {
            if (amount > 0)
            {
                balance += amount;
            }
        }

        public void Withdraw(double amount)
        {
            if (amount > 0 && amount <= balance)
            {
                balance -= amount;
            }
        }

        public double GetBalance()
        {
            return balance;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BankAccount account = new BankAccount();
            account.Deposit(100);
            account.Withdraw(30);
            Console.WriteLine($"Current balance: {account.GetBalance()}");
        }
    }
}

이 예제에서 BankAccount 클래스는 balance 필드를 private으로 선언하여 외부에서 직접 접근할 수 없도록 하고, Deposit, Withdraw, GetBalance 메서드를 통해서만 접근할 수 있도록 합니다.

객체 지향 프로그래밍은 코드의 재사용성을 높이고, 유지보수를 용이하게 하며, 논리적 구조를 명확히 하는 데 큰 도움을 줍니다. C#을 통해 객체 지향 프로그래밍의 강력한 기능을 활용할 수 있습니다.


Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *