프로그래밍/C#
C# 상속(Inheritance), virtual, override 키워드 정리
MutJangE
2024. 11. 13. 21:32
반응형
상속(Inheritance)
부모 클래스로부터 기능들을 자식 클래스가 물려받는 행위이다.
- 부모 클래스의 기능을 재사용하고, 확장이 가능하다.
- 생산성과 유지보수에 크게 도움이 된다.
C#에서 상속(Inheritance) 사용하기
public class Doctor // 부모 클래스 Doctor 생성
{
private void Leave() // 접근 불가능
{
Console.WriteLine("퇴근을 합니다.");
}
protected void Claim(int money) // 접근 가능
{
Console.WriteLine($"돈 {money} 원을 청구합니다.");
}
public void Health(string name) // 접근 가능
{
Console.WriteLine($"환자 {name} 님을 치료합니다.");
}
}
public class Customer : Doctor // 자식 클래스 Customer가 부모 클래스 Doctor를 상속
{
public Customer()
{
Health("홍길동");
Claim(10000);
}
}
public class Program
{
public static void Main(string[] args)
{
new Customer();
}
}
/* 환자 홍길동 님을 치료합니다.
돈 10000 원을 청구합니다. */
접근 제어자 | 같은 클래스 | 같은 패키지 or 네임스페이스 | 자식 클래스 | 외부 클래스 |
private | 가능 | 불가능 | 불가능 | 불가능 |
default | 가능 | 가능 | 불가능 | 불가능 |
protected | 가능 | 가능 | 가능 | 불가능 |
public | 가능 | 가능 | 가능 | 가능 |
BASE 키워드와 THIS 키워드
public class Doctor
{
public int myMoney = 1500;
}
public class Customer : Doctor
{
new int myMoney = 100; // 앞에 new 키워드를 붙이면 해당 변수는 상속 받지않음.
public Customer()
{
Console.WriteLine($"내 돈 : {this.myMoney}원");
Console.WriteLine($"의사 돈 : {base.myMoney}원");
}
}
public class Program
{
public static void Main(string[] args)
{
new Customer();
}
}
/* 내 돈 : 100원
의사 돈 : 1500원 */
virtual 키워드와 override 키워드
public class Doctor
{
public virtual void Talk() // Talk() 메소드를 추상화
{
Console.WriteLine("의사가 말을 합니다.");
}
}
public class Customer : Doctor
{
public override void Talk() // 추상화 된 Talk() 메소드를 override로 재정의
{
Console.WriteLine("환자가 말을 합니다.");
}
public Customer()
{
base.Talk(); // Doctor.Talk()
this.Talk(); // Customer.Talk()
}
}
public class Program
{
public static void Main(string[] args)
{
new Customer();
}
}
/* 의사가 말을 합니다.
환자가 말을 합니다. */
반응형