🍀 Unity

[C#] 상속과 유효범위(scope)

수구마 2025. 6. 1. 18:49

상속


기존 클래스의 기능을 이어받아 확장하는 개념

코드 재사용성을 좋게 하기 위함

 

부모 클래스를 상속받아 자식 클래스를 만든다.

부모 클래스보다 자식 클래스의 기능이 더 많음

 

 

부모클래스 Character  
public class Character
{
    public string name;
    public int hp;

    public void Heal (int healHP)
    {
       ...
    }

    public void Hit(int damage)
    {
        ...
    }

    public bool isAlive()
    {
        ...
    }
}
public class Wizard
{

    // Character 와 중복되는 부분
    public string name;
    public int hp;

    public void Heal (int healHP)
    {
       ...
    }

    public void Hit(int damage)
    {
        ...
    }

    public bool isAlive()
    {
        ...
    }

    // 중복되지 않는 부분
    public float mp;

    public void UseMagic()
    {
        ...
    }
}
 

Character를 상속받은 자식클래스 Wizard
  public class Wizard : Character
{
    public float mp;

    public void UseMagic()
    {
        ...
    }
}

 

Wizard 타입의 변수에는 Character를 대입할 수 있지만 반대는 불가능

 

 Wizard aWizard = new Wizard();

 Character aMan = aWizard; // 가능

 Character aCharacter = new Character();

 Wizard aWizard2 = aCharacter; // 에러

Wizard aWizard2 = (Wizard)aCharacter;

억지로 타입캐스팅을 해서 코드상으로는 에러가 없지만 실행하면 잘못된 형변환 에러가 발생

 

 

가시성 유효범위 scope

 

{ }로 코드 블록을 나눌 수 있다.

 

중괄호 바깥에서 선언된 변수를 중괄호 안에서 다시 선언하면 에러가 발생함

    void Start()
    {
        for(int i = 0; i < 10; i++)
        {
            int x = 0;
            Debug.Log(x);
        }

        int x = 1;
        Debug.Log(x);
    }

 

 

public class HelloWorld : MonoBehaviour
{
    int x = 1;
    void Start()
    {
        for(int i = 0; i < 10; i++)
        {
            int x = 0;

            Debug.Log(x);
            Debug.Log(this.x);
        }

  
    }

}

 

this.x는 HelloWorld라는 클래스 자체의 x를 의미함 (클래스의 인스턴스)

for문 안에서 x는 함수 안에서 선언된 x를 의미함

 

public, private

밖에서 볼 필요 없는 내용을 감춤 (캡슐화)

 

public은 어디서나 사용할 수 있는 변수

private는 해당 객체 안에서만 접근할 수 있는 변수

 

변수 선언시 기본값은 private

 

protected는 public과 private사이의 속성

관계된 객체(부모-자식 클래스)에서만 접근 가능