상위 클래스는 부모 클래스, 베이스 클래스
하위 클래스는 자식 클래스, 파생 클래스
여러 개의 클래스가 하나의 클래스에게 상속 받는 것은 가능
하나의 클래스가 여러개의 클래스를 상속받는 다중 상속은 X
class Adult : Human
{
public Adult(string _name, int _age, float _height) : base(_name, _age, _height){}
}
class Baby : Human
{
public Baby(string _name, int _age, float _height) : base(_name, _age, _height){}
}
상속은 위와 같이 하위 클래스의 이름 뒤에 콜론( : )
상속 → Human 클래스가 가지는 필드와 메서드를 그대로 가져감 → 코드 감소
다만 자식 클래스가 부모 클래스의모든 것을 상속 받는 것은 X → 접근 제한자로 조절 가능
this 현재 객체를 가리키는 키워드 (this를 생략해도 됨)
public Human(string name, int age, float height)
{
this.name = name;
this.age = age;
this.height = height;
}
base는 현재 객체의 부모 클래스를 가리키는 키워드
void Start()
{
Adult maria = new Adult("maria", 10, 12);
maria.Age = 1;
maria.SetBaseAge(2);
Debug.Log(maria.Age);
Debug.Log(maria.GetBaseAge());
}
class Adult : Human
{
public Adult(string _name, int _age, float _height) : base(_name, _age, _height){}
public int Age;
public void SetBaseAge(int age)
{
base.age = age;
}
public int GetBaseAge()
{
return base.age;
}
}