namespace CScodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Student std = new Student(13, 6);
        }
    }
}

public class Person
{
    int _age;

    public Person()
    {
        Console.WriteLine("People_1");
    }

    public Person(int age) 
    {
        Console.WriteLine("People_2");
        _age = age;
    }
}

public class Student : Person
{
    string _school;

    public Student(int age, int year)
    {
        Console.WriteLine("Student_1");
    }
}

public class Employee : Person
{
    string _company;

    public Employee(int age, string company)
    {
        Console.WriteLine("Employee_1");
    }
}

결과 :

Hello World!
People_1
Student_1

자식 클래스인 Student를 인스턴스화 시 자동으로 부모 클래스의 생성자가 호출 됨(매개변수가 없는 default 생성자가 호출되고 있음)

 

매개변수가 void인 생성자가 만약 없을 시 

namespace CScodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Student std = new Student(13, 6);
        }
    }
}

public class Person
{
    int _age;

    /*
    public Person()
    {
        Console.WriteLine("People_1");
    }
    */

    public Person(int age) 
    {
        Console.WriteLine("People_2");
        _age = age;
    }
    
}

public class Student : Person
{
    string _school;

    public Student(int age, int year)
    {
        Console.WriteLine("Student_1");
    }
}

public class Employee : Person
{
    string _company;

    public Employee(int age, string company)
    {
        Console.WriteLine("Employee_1");
    }
}

오류 발생 

자식생성자에서 부모생성자를 호출하지 못하게 때문에 오류 발생.
이럴때는 이니셜라이즈를 통해 base 키워드를 사용하여 부모 생성자 호출해야 됨.

 

namespace CScodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Student std = new Student(13, 6);
        }
    }
}

public class Person
{
    int _age;

    /*
    public Person()
    {
        Console.WriteLine("People_1");
    }
    */

    public Person(int age) 
    {
        Console.WriteLine("People_2");
        _age = age;
    }
    
}

public class Student : Person
{
    string _school;

    public Student(int age, int year) : base(age)
    {
        Console.WriteLine("Student_1");
    }
}

public class Employee : Person
{
    string _company;

    public Employee(int age, string company) : base(age)
    {
        Console.WriteLine("Employee_1");
    }
}

 

 

+ Recent posts