C#/클래스와 객체지향
C# 클래스와 객체지향 - 14. 상속의 생성자
tita
2024. 5. 28. 21:55
상속했을 때 생성자 메서드가 어떻게 되는지 알아보겠습니다.
생성자는 인스턴스를 초기화할 때 사용합니다. 자식 인스턴스를 생성하면, 부모가 가지고 있는 멤버 초기화를 위해 부모 생성자도 자동으로 호출됩니다.
class Program
{
class Parent
{
public Parent()
{
Console.WriteLine("부모 생성자");
}
}
class Child : Parent
{
public Child()
{
Console.WriteLine("자식 생성자");
}
}
static void Main(string[] args)
{
// 자식 인스턴스 생성
Child child = new Child();
}
}
/*
[실행 결과]
부모 생성자
자식 생성자
*/
코드를 실행하면 부모 생성자가 먼저 호출됩니다. 그 이후 자식 생성자가 호출되며 이것은 굉장히 중요합니다.
만약 부모 생성자 호출을 명시적으로 지정하고 싶은 경우에는 base 키워드를 사용하면 됩니다.
생성자 메서드 뒤에 콜론을 입력하고 base()를 입력하면 됩니다.
base()를 사용하는 예제도 확인해보겠습니다.
class Program
{
class Parent
{
public Parent() { Console.WriteLine("Parent()"); }
public Parent(int param) { Console.WriteLine("Parent(int param)"); }
public Parent(string param) { Console.WriteLine("Parent(string param)"); }
}
class Child : Parent
{
public Child() : base(10) //Parent(int param) 부모 생성자를 호출합니다.
{
Console.WriteLine("Child() : base(10)");
}
public Child(string input) : base(input) //Parent(string param) 부모 생성자를 호출합니다.
{
Console.WriteLine("Child(string input) : base(input)");
}
}
static void Main(string[] args)
{
Child childA = new Child();
Child childB = new Child("string");
}
}
/*
[실행 결과]
Parent(int param)
Child() : base(10)
Parent(string param)
Child(string input) : base(input)
*/