C#문법

[C# 문법] Part18 접근 제한자 (public, private, protected)

BlackWolfDev 2025. 2. 2. 23:34

[ 개요 ]

오늘은 C#의 핵심 개념 중 하나인 접근 제한자에 대해 알아보자.

접근 제한자는 클래스의 멤버(필드, 메서드 등)에 대한 접근 범위를 제어하는 중요한 개념이다.


[ 접근 제한자의 종류 ]

C#에서 주로 사용되는 접근 제한자는 다음과 같다.

  1. public: 어디서든 접근 가능
  2. private: 같은 클래스 내에서만 접근 가능
  3. protected: 같은 클래스 및 파생 클래스에서 접근 가능

[ 활용법 ]

부모 클래스인 Charater을 아래와 같이 구현했다고 가정하자.

public class Character
{
    // private 필드 - 클래스 내부에서만 접근 가능
    private int health;
    private int mana;
    private string playerName;

    // protected 필드 - 상속받은 클래스에서도 접근 가능
    protected int level;
    protected int experience;

    // public 프로퍼티 - 어디서든 접근 가능
    public int Health 
    { 
        get { return health; }
        private set { health = value; } // setter는 private으로 제한
    }

    // public 생성자
    public Character(string name)
    {
        this.playerName = name;
        this.health = 100;
        this.mana = 50;
        this.level = 1;
        this.experience = 0;
    }

    // public 메서드 - 외부에서 호출 가능
    public void TakeDamage(int damage)
    {
        CalculateDamage(damage); // private 메서드 호출
        CheckHealth(); // private 메서드 호출
    }

    // private 메서드 - 클래스 내부에서만 사용
    private void CalculateDamage(int damage)
    {
        health -= damage;
    }

    private void CheckHealth()
    {
        if (health <= 0)
        {
            Die();
        }
    }

    // protected 메서드 - 상속받은 클래스에서 사용 가능
    protected virtual void Die()
    {
        Console.WriteLine($"{playerName} has been defeated!");
    }
}

 

Character를 상속 받는 Warrior클래스가 있다고 하면 아래와 같이 된다.

public class Warrior : Character
{
    // private 필드
    private int rage;

    public Warrior(string name) : base(name)
    {
        this.rage = 0;
    }

    // protected 메서드 오버라이드
    protected override void Die()
    {
        // level은 protected이므로 접근 가능
        Console.WriteLine($"Level {level} Warrior has fallen in battle!");
        
        // health는 private이므로 직접 접근 불가능
        // 단, public 프로퍼티를 통해 접근 가능
        Console.WriteLine($"Final Health: {Health}");
    }
}

[ 접근 제한자 사용 가이드라인 ]

1. private 사용 시기

  • 클래스의 내부 구현 세부사항을 숨기고 싶을 때
  • 데이터의 직접적인 수정을 방지하고 싶을 때
  • 내부적으로만 사용되는 헬퍼 메서드들
public class Inventory
{
    private Item[] items; // 배열은 내부 구현이므로 private
    private int maxSlots; // 최대 슬롯 수도 내부 구현

    public bool AddItem(Item item)
    {
        if (HasSpace()) // private 메서드 호출
        {
            return TryAddItem(item); // private 메서드 호출
        }
        return false;
    }

    private bool HasSpace()
    {
        // 내부 로직
        return true;
    }

    private bool TryAddItem(Item item)
    {
        // 내부 로직
        return true;
    }
}

 

2. protected 사용 시기

  • 부모 클래스의 기능을 자식 클래스에서 재사용하거나 확장해야 할 때
  • 상속 계층에서 공통으로 사용되는 기능을 구현할 때
public class Spell
{
    protected float manaCost;
    protected float castTime;

    protected virtual void StartCasting()
    {
        // 기본 캐스팅 로직
    }
}

public class Fireball : Spell
{
    protected override void StartCasting()
    {
        base.StartCasting();
        // 파이어볼 특화 캐스팅 로직 추가
    }
}

 

3. public 사용 시기

  • 외부에서 접근해야 하는 API를 제공할 때
  • 다른 클래스에서 사용해야 하는 기능을 노출할 때
public class GameManager
{
    public void StartGame()
    {
        // 게임 시작 로직
    }

    public void PauseGame()
    {
        // 게임 일시정지 로직
    }

    public void SaveGame()
    {
        // 게임 저장 로직
    }
}

[ 주의사항 ]

 

  1. 불필요하게 public으로 선언하지 않기
  2. private으로 시작하고 필요할 때만 접근 범위 넓히기
  3. protected는 상속 관계에서 정말 필요할 때만 사용하기

[ 접근제한자의 장점 ]

 

  1. 코드의 안정성 향상
  2. 유지보수성 개선
  3. 불필요한 의존성 감소
  4. 코드 재사용성 증가

 

 

728x90
반응형

'C#문법' 카테고리의 다른 글

[C# 문법] Part19 프로퍼티(Property)  (3) 2025.02.02
[C# 문법] Part17 const 키워드  (0) 2025.02.02
[C# 문법] Part16 static 한정자  (1) 2024.10.19
[C#문법] Part15 this 키워드  (2) 2024.10.12
[C#문법] Part14 new 연산자  (7) 2024.10.09