Menu
Coddy logo textTech

생성자

Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 70개 중 7번째.

constructor는 객체를 Create할 때 실행되는 특수한 메서드입니다. 객체의 properties와 필드를 초기화합니다.

parameters가 없는 Default 생성자

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // 기본 생성자
    public Book()
    {
        Title = "Unknown";
        Author = "Unknown";
    }
}

매개변수가 있는 생성자

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // 매개변수가 있는 생성자
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

생성자 오버로딩 - 여러 생성자

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // 매개변수가 두 개인 생성자
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
        Pages = 0;
    }
    
    // 매개변수가 세 개인 생성자
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
}

this를 사용한 생성자 체이닝

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // 메인 생성자
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
    
    // 기본 페이지로 메인 생성자를 호출합니다
    public Book(string title, string author) : this(title, author, 0)
    {
    }
}

서로 다른 생성자를 사용하여 객체 만들기

Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);

Constructor는 클래스와 같은 이름을 가지며 반환 유형이 없습니다. new 키워드를 사용하면 자동으로 실행됩니다. 서로 다른 parameters를 사용하는 여러 Constructor를 정의할 수 있습니다(오버로딩).

challenge icon

챌린지

중급

생성자 오버로딩과 체이닝을 사용하여 Product 클래스에 세 개의 생성자를 만드세요:

  • 3개의 parameters를 사용하는 생성자: name, price, stock
  • 2개의 parameters를 사용하는 생성자: name과 price (stock은 0으로 기본 설정됨)
  • parameters가 없는 default 생성자 (name = "Unknown", price = 0, stock = 0)

코드 중복을 피하기 위해 this를 사용하여 생성자 체이닝을 구현하세요.

직접 해보기

using System;

class Program
{
    static void Main()
    {
        string name = Console.ReadLine();
        decimal price = decimal.Parse(Console.ReadLine());
        int stock = int.Parse(Console.ReadLine());
        
        Product product1 = new Product(name, price, stock);
        Product product2 = new Product();
        Product product3 = new Product("Keyboard", 79.99m);
        
        Console.WriteLine($"Product 1: {product1.Name} - ${product1.Price} (Stock: {product1.Stock})");
        Console.WriteLine($"Product 2: {product2.Name} - ${product2.Price} (Stock: {product2.Stock})");
        Console.WriteLine($"Product 3: {product3.Name} - ${product3.Price} (Stock: {product3.Stock})");
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러