프로그래밍/C#

[C#] virtual, abstract, interface

준코딩 2020. 11. 5. 14:33

 Virtual (가상)

 

  1.  abstract 와는 다르게 본문을 정의할 수 있습니다. (비워 놓아도 됨)

  2. 파생 클래스에서 재정의 할 수 있습니다.

  3. 자식 클래스에서는 new 또는 override 키워드 사용이 가능합니다.

    • override는 재정의 또는 확장의 의미

    • new는 기본 클래스를 숨긴다는 의미

  4. base. 키워드를 통해 부모 클래스의 함수 호출이 가능합니다.

  5. private, static 등 접근 한정자는 사용할 수 없습니다.

 

<  예제 코드  >

더보기

 

    public  class Parent
    {
        public virtual void func1() { }
    }

    public class Child : Parent
    {
        public override void func1()
        {
            base.func1();
            Console.WriteLine("재정의");
        }
    }

 

 

 

 Abstract (추상)

 

  1. 메서드에 사용하려면 해당 클래스도 abstract로 선언되어야 합니다.

  2. 해당 키워드로 선언된 메서드는 본문을 정의할 수 없습니다.

  3. 자식 클래스는 반드시 부모의 abstract 메서드를 재정의 해야 합니다.

  4. private 키워드를 사용할 수 없습니다.

  5. 새로운 객체 생성이 안됩니다. ex) Example exam = new Example(); -> x

 

< 예제 코드 >

 

더보기
    abstract class Parent
    {
        public abstract void func1();
        public abstract void func2();
    }

    class Child : Parent
    {
        public override void func1()
        {
            throw new NotImplementedException();
        }

        public override void func2()
        {
            throw new NotImplementedException();
        }
    }

 

 

 Interface

  1. 인터페이스는 객체를 생성할 수 없습니다.

  2. 멤버변수를 포함할 수 없습니다.

  3. 접근 제한자는 public 만을 지원합니다.

  4. 인터페이스의 메서드를 자식 클래스에서 구현할 경우 반드시 public을 사용해야 합니다.

  5. 다중 상속이 가능합니다.(클래스는 다중 상속이 불가능)

  6. 인터페이스의 모든 메서드를 자식클래스에서 재정의 해야합니다.

 

< 예제 코드 >

더보기
   interface Inter1
    {
        void inter1();
    }

    interface Inter2
    {
        void inter2();
    }

    interface Inter3
    {
        void inter3();
    }

    public class Child : Inter1, Inter2, Inter3
    {
        public void inter1()
        {
            throw new NotImplementedException();
        }

        public void inter2()
        {
            throw new NotImplementedException();
        }

        public void inter3()
        {
            throw new NotImplementedException();
        }
    }