생성자
Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 70개 중 7번째.
생성자는 객체를 생성할 때 실행되는 특별한 메서드입니다. 이것은 객체의 속성과 필드를 초기화합니다.
매개변수가 없는 기본 생성자
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);생성자는 클래스와 이름이 같고 반환 타입이 없습니다. new 키워드를 사용할 때 자동으로 실행됩니다. 서로 다른 매개변수를 가진 여러 개의 생성자를 가질 수 있습니다(오버로딩).
챌린지
중급생성자 오버로딩과 체이닝을 사용하여 Product 클래스를 위한 세 개의 생성자를 만드세요:
- 3개의 매개변수를 가진 생성자: name, price, stock
- 2개의 매개변수를 가진 생성자: name 및 price (stock의 기본값은 0)
- 매개변수가 없는 기본 생성자 (name = "Unknown", price = 0, stock = 0)
코드 중복을 피하기 위해 this를 사용한 생성자 체이닝을 활용하세요.
치트 시트
생성자(Constructor)는 객체를 생성할 때 실행되는 특별한 메서드입니다. 이는 객체의 속성을 초기화합니다.
생성자는 클래스와 동일한 이름을 가지며 반환 형식이 없습니다. new 키워드를 사용할 때 자동으로 실행됩니다.
매개변수가 없는 기본 생성자(Default constructor):
public class Book
{
public string Title { get; set; }
public Book()
{
Title = "Unknown";
}
}매개변수가 있는 생성자(Parameterized constructor):
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
}생성자 오버로딩(Constructor overloading) - 매개변수가 다른 여러 생성자:
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
public Book(string title)
{
Title = title;
Pages = 0;
}
public Book(string title, int pages)
{
Title = title;
Pages = pages;
}
}코드 중복을 피하기 위해 this를 사용한 생성자 체이닝(Constructor chaining):
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
public Book(string title, int pages)
{
Title = title;
Pages = pages;
}
public Book(string title) : this(title, 0)
{
}
}서로 다른 생성자를 사용하여 객체 생성하기:
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);직접 해보기
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})");
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.