- 읽기 전용 필드(readonly)
- 변수를 정의할 때와 생성자를 제외하고는 그 값을 바꿀 수 없다.
- setter 없이 구현하면 readonly를 사용하지 않아도 외부에서 값을 바꿀 수 없기는 하지만, readonly를 사용하면 클래스 내부에서도 값의 불변을 보장한다.
✍ 샘플 코드
class Marriage
{
readonly int year = 2020;
readonly string groom;
readonly string bride;
Boolean isDivorced;
int children;
public Marriage(string groom, string bride)
{
this.groom = groom;
this.bride = bride;
}
public void changeSpouse(string newName)
{
this.groom = newName;
}
public void changeYear(int year)
{
this.year = year;
}
public void getChild()
{
children++;
}
public void getDivorce(Boolean divorce)
{
this.isDivorced = divorce;
}
}
- 상수(const)
- 변하지 않는 값인 리터럴에 식별자를 붙인 것이다.
✍ 샘플 코드
class Marriage
{
const string requirement = "Love";
const Boolean isImportant = true;
}
- readonly vs const
- 상수는 static 예약어가 허용되지 않는다.(의미상 이미 static에 해당한다.)
- 상수는 기본자료형에 대해서만 정의가 허용된다.
- 상수는 정의 시 값을 대입해야 한다. 즉, 생성자에 접근할 수 없다.
- 상수는 컴파일할 때 해당 소스코드에 값이 직접 치환된다.