반응형
가상(Virtual) 함수란?
- 부모 클래스에서 virtual 키워드를 사용하여 함수를 만들면 자식 클래스에서 해당하는 함수를 재정의 할 수 있도록 허락한다는 의미이다.
- 자식 클래스에서 override 또는 new 키워드가 사용 가능하다.
- override는 재정의 new는 새로운 함수이다.(아무런 키워드를 사용하지 않을 시 new와 동일)
- 자식클래스의 함수에서 base 키워드를 사용하여 부모 클래스의 함수를 호출 할 수 있다.
- 추상(abstract)과는 달리 자식에서의 구현은 선택이다.
- static, abstract, private, override 키워드와는 함께 사용할 수 없다.
예시
public class Animal
{
public virtual void walk()
{
Console.WriteLine("Animal walk");
}
}
public class dog : Animal
{
public override void walk() //오버라이딩
{
Console.WriteLine("dog walk");
}
}
public class cat : Animal
{
public new void walk() //새로생성
{
Console.WriteLine("cat walk");
}
}
public class hedgehog : Animal
{
public void walk() //새로 생성
{
Console.WriteLine("hedgehog walk");
}
}
class VirtualStudy
{
static void Main(stirng[] args)
{
Animal animal1 = new Animal();
dog animal2 = new dog();
cat aniaml3 = new cat();
hedgehog animal4 = new hedgehog();
animal1.walk();
animal2.walk();
animal3.walk();
animal4.walk();
Animal animal5 = new dog();
Animal animal6 = new cat();
Animal animal7 = new hedgehog();
animal4.walk();
animal5.walk();
animal6.walk();
}
}
//출력 결과
//Animal walk
//dog walk
//cat walk
//hedgehog walk
//dog walk
//Aniaml walk
//Aniaml walk
- dog만 walk 함수를 override 했기 때문에 Animal클래스에 dog를 담았을때 dog walk가 출력될 수 있다.
반응형
'C#' 카테고리의 다른 글
[c#] delegate 와 Event (0) | 2022.06.30 |
---|---|
[c#] 추상클래스와 추상 메서드(abstract) (0) | 2021.08.20 |
[c#] Boxing 과 Unboxing (0) | 2021.08.20 |
[c#] 코루틴과 Invoke (0) | 2021.08.09 |
[c#] 스레드와 코루틴 (0) | 2021.08.09 |