백지부터 시작하는 이세계 코딩 생활
키워드 this 와 Base 본문
this
this 는 클래스의 현재 객체를 가리키는 키워드이다. 클래스의 맴버 변수에 접근하기 위해 사용한다.
맴버 변수에 접근하기 위해 객체를 이용해야 한다. 따라서 멤버가 정의된 클래스 내의 멤버에 접근하기 위해서
현재 객체를 가리키는 this 키워드를 사용된다.
* 보통 클래스 내 멤버변수에 접근하고자 할 때 생략된 채로 사용한다.
* this 키워드를 사용하면 사용되고 있는 클래스의 객체를 가리키게 된다. (자기 자신의 생성자를 지칭한다)
* i.e ) 자신의 인스턴스를 가리키게 된다는 것과도 같다.
* static 변수는 클래스 자체에 속하기 때문에 this를 이용해 접근할 수 없다.
base
base 키워드는 상속관계에 있는 상위클래스를 가리킨다.
때문에 키워드 base는 상속관계에서 상위클래스의 맴버에 접근하기 위해 사용하는 키워드이다.
상속관계에 있는 하위클래스 매서드에서 상위클래스 매서드를 호출하거나,
상속받은 상위클래스 매서드를 하위클래스 매서드에서 재정의 (override) 하기 위해 사용한다.
using UnityEngine;
public class Human
{
public string name;
public int age;
public float tall;
public Human() { }
public Human(string _name, int _age, float _tall)
{
this.name = _name;
this.age = _age;
this.tall = _tall;
}
}
using UnityEngine;
public class Inheritance : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
D_Child D = new D_Child("JJOADUCK_lover", 2012, 11.0f);
D.GetBaseName(base.name);
D.SetBaseName(this.name);
D.GetBaseName(base.name);
}
class D_Child : Human
{
public D_Child(string _name, int _age, float _tall) : base(_name, _age, _tall) { }
public void SetBaseName(string _name)
{
_name = "JJOADUCK 5252";
this.name = _name;
print("here is SetBaseName --> this.name : " + this.name);
}
public string GetBaseName(string _name)
{
print("here is GetBaseName --> base.name : " + base.name);
return base.name;
}
}
}
'백지부터 시작하는 이세계 유니티 생활 since 2020' 카테고리의 다른 글
Encapsulation (캡슐화) with Access modifier (접근제한자) (0) | 2020.12.09 |
---|---|
Constructor ( 생성자 ), Destructor ( 소멸자 ) (0) | 2020.12.09 |
Inheritance (0) | 2020.12.09 |
Object Pool (0) | 2020.12.04 |
Memory 구조 (0) | 2020.12.04 |
Comments