jae_coding

[유니티로 배우는 C#] 상속 본문

C#

[유니티로 배우는 C#] 상속

재코딩 2022. 7. 19. 11:56
반응형

상속

상위 클레스에 있는 변수나 함수를 사용하기 위함

 

상위 클레스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Human : MonoBehaviour
{
    // protected는 상속받은 클레스에서만 사용가능하다.
    protected string humanName;
    protected int humanage;

    // virtual 하위 클레스에서 함수를 재정의할 수 있도록 만든다.
    protected virtual void Info(){
        print("나는 인간입니다.");
    }

    //추가적인 변수를 넣어주기 위함 (완성은 자식클레스에서 완성시킬 수 있다. 이때는 하위 클레스에서 abstract를 지정해줘야함)
    abstract protected void Name();

}

하위 클레스

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

abstract public class Student : Human
{
    string schoolName;

    void Start(){
        schoolName = "jae초등학교";
        // 변수 상속
        humanName = "jae";
        humanage = 12;
    }

    // 상위 클레스에서의 함수 재정의, 가상함수에서만 사용가능
    protected override void Info()
    {
        base.Info();
        print("나는 학생입니다");
    }

    protected override void Name()
    {
        print(humanName);
    }
}

강의자료: 케이디 유튜브

반응형
Comments