C#/C#200제
[C#] 10일차 - 68. 생성자 메소드
반나무
2021. 1. 30. 15:07
Date christmas = new Day(2021, 12, 25);
객체가 만들어지면서 수행해야 하는 작업을 생성자라고 하는 특별한 메소드에 코딩합니다.
생성자메소드의 이름은 클래스의 이름과 같고 return 값이 없으며 중복해서 정의할 수 있습니다.
구조체도 생성자를 가질 수 있습니다. 다만 구조체에서는 매개변수가 없는 생성자는 사용할 수 없습니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A068_Constuctor
{
class Date
{
private int year, month, day;
// 매개변수 없는 Date() 생성자
public Date()
{
year = 1;
month = 1;
day = 1;
}
// 매개변수 있는 Date생성자
public Date (int y, int m, int d)
{
year = y;
month = m;
day = d;
}
public void PrintDate()
{
Console.WriteLine("{0}/{1}/{2}", year, month, day);
}
}
class Program
{
static void Main(string[] args)
{
Date birthday = new Date(2000, 11, 22);
Date christmas = new Date(2021, 12, 25);
Date firstDay = new Date();
birthday.PrintDate();
christmas.PrintDate();
firstDay.PrintDate();
}
}
}
반응형