백지부터 시작하는 이세계 코딩 생활
Inheritance 본문
상속 ( Inheritance )
상속이란 하나의 클래스가 다른 클래스의 속성( 멤버 변수 ) 및 기능( 매서드 ) 을 사용할 수 있게 하는 것을 뜻한다.
i.e ) 상위클래스의 코드를 하위클래스에서 이어받아 사용할 수 있게 하는 개념이다. 확장의 개념.
상속은 IS - A 관계 ( is a realtionship; inheritance ) 에서 사용하는 것이 가장 효율적이다. IS-A 관계는 추상적인 개념과 구체적인 개념의 관계이다. 따라서 추상적인 클래스를 점차 구체화 하기 위해 사용하는 것이 좋다.
객체지향의 특징 중 한가지 이다.
상속해주는 클래스를 상위클래스(super class), 부모클래스(parent class), 베이스클래스(base class) 라고 부르며
상속받는 클래스를 하위클래스(sub class), 자식클래스(child class), 파생클래스(derived class) 라고 부른다.
특징 및 주의 :
* 유지보수에 편리성을 가진다. 상속관계에 있을 때, 베이스클래스가 수정되면 파생클래스에서도 수정된다.
* Base Class 는 여러개의 파생클래스를 가질 수 있다. (그림 참고)
* 파생클래스는 단 하나의 베이스클래스만을 가질 수 있다.
* 파생클래스는 베이스클래스의 private 접근 허용자를 제외한 다른 속성과 기능을 모두 사용할 수 있다.
접근허용자 :
사용법 :
* 파생클래스 이름 뒤에 : (세미콜론) 을 붙이고 베이스클래스 명을 작성하고 사용한다.
* 상속 할 때, 베이스클래스에 생성자를 만들어 준다.
* 베이스 클래스에 직접 접근할 때, 구현하고자 하는 클래스에서 새롭게 인스턴스(Instance) 를 만들어줘야 한다.
// BASE Class (베이스클래스, 상위클래스)
using UnityEngine;
public class Human
{
public string name;
public int age;
public float tall;
public Human(string _name, int _age, float _tall) //생성자 (이름, 나이, 키를 매개변수로 받고 있다)
{
this.name = _name;
this.age = _age;
this.tall = _tall;
}
public void Play()
{
Debug.Log("this is human class --> play method");
}
public void Eat()
{
Debug.Log("this is human class --> eat method");
}
}
// derived Class (파생클래스, 하위클래스)
using UnityEngine;
public class InheritanceExample : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
A_Child A = new A_Child("JJOA", 199, 1.0f);
B_Child B = new B_Child("Duck", 10, 5.0f);
print("this is start method, A : " + A);
print("this is start method, B : " + B);
Human H = new Human("HamHuman", 20, 1209);
H.Eat();
H.Play();
}
class A_Child : Human
{
public A_Child(string _name, int _age, float _tall) : base(_name, _age, _tall)
{
print("this is A_Child class --> A_Child method --> A_Child property : " + _name + _age + _tall);
}
}
class B_Child : Human
{
public B_Child(string _name, int _age, float _tall) : base(_name, _age, _tall)
{
print("this is B_Child class --> B_Child method --> B_Child property : " + _name + _age + _tall);
}
}
}
Result :
'백지부터 시작하는 이세계 유니티 생활 since 2020' 카테고리의 다른 글
Constructor ( 생성자 ), Destructor ( 소멸자 ) (0) | 2020.12.09 |
---|---|
키워드 this 와 Base (0) | 2020.12.09 |
Object Pool (0) | 2020.12.04 |
Memory 구조 (0) | 2020.12.04 |
Shader (0) | 2020.12.01 |