프로그래밍 언어/C#

[C#] 생성자와 상속

ShovelingLife 2023. 9. 22. 11:52

자식 클래스에서 부모클래스로 접근은 가능하지만 자식클래스에서 부모클래스의 생성자는 자동으로 상속되지 않는다.

class Parent
{
    public int X;
    public Parent() { }
    public Parent(int X)
    {
        this.X = X;
    }
}

class Child : Parent
{

}

class Program
{
    static void Main(string[] args)
    {
        Child child = new Child(123); //컴파일에러
        Console.WriteLine(child.X);
    }
}

 

자식클래스는 자신이 노출하고자 하는 생성자들을 반드시 '다시 정의' 해야한다.

class Parent
{
    public int X;
    public Parent() { }
    public Parent(int X)
    {
        this.X = X;
    }
}

class Child : Parent
{
    public Child(int X) : base(X) { } //base 키워드를 사용하여 상속
}

class Program
{
    static void Main(string[] args)
    {
        Child child = new Child(123);
        Console.WriteLine(child.X);
    }
}

 

만약 base키워드를 쓰지 않고 매개변수가 없는 생성자를 호출하면 부모클래스의 매개변수가 없는 생성자가 실행된다.

부모클래스에 접근 가능한 기본생성자가 하나도 없으면 자식클래스는 생성자에서 반드시 base클래스를 사용해야한다.

class Parent
{
    public int X;
    public Parent() { }
    public Parent(int X)
    {
        this.X = X;
    }
}
class Child : Parent
{
    public int y;
}
class Program
{
    static void Main(string[] args)
    {
        Child child = new Child();
        Console.WriteLine(child.X);
    }
}

 

 

20200217[C#] 생성자와 상속 :: 뻔뻔한블로그 (tistory.com)