다음을 통해 공유


인터페이스 기반 다형성

업데이트: 2007년 11월

인터페이스는 Visual Basic에서 다형성을 구현하는 또 다른 방법입니다. 인터페이스는 클래스처럼 속성과 메서드를 설명하지만, 클래스와는 다르게 어떠한 구현도 제공하지 않습니다. 여러 개의 인터페이스를 사용하면 기존 코드를 손상시키지 않고 소프트웨어 구성 요소 시스템을 향상시킬 수 있다는 이점이 있습니다.

인터페이스로 다형성을 구현하려면 여러 클래스에서 서로 다른 방식으로 인터페이스를 구현하십시오. 클라이언트 응용 프로그램은 이전 구현과 새 구현을 같은 방식으로 사용할 수 있습니다. 인터페이스 기반 다형성의 장점은 새 인터페이스 구현에서 작동되도록 하기 위해 기존 클라이언트 응용 프로그램을 다시 컴파일할 필요가 없다는 점입니다.

다음 예제에서는 RightTriangleClass2 및 RectangleClass2 클래스에 구현된 Shape2 인터페이스를 정의합니다. ProcessShape2 프로시저는 다음과 같이 RightTriangleClass2 또는 RectangleClass2 클래스 인스턴스의 CalculateArea 메서드를 호출합니다.

Sub TestInterface()
    Dim RectangleObject2 As New RectangleClass2
    Dim RightTriangleObject2 As New RightTriangleClass2
    ProcessShape2(RightTriangleObject2, 3, 14)
    ProcessShape2(RectangleObject2, 3, 5)
End Sub

Sub ProcessShape2(ByVal Shape2 As Shape2, ByVal X As Double, _
      ByVal Y As Double)
    MsgBox("The area of the object is " _
       & Shape2.CalculateArea(X, Y))
End Sub

Public Interface Shape2
    Function CalculateArea(ByVal X As Double, ByVal Y As Double) As Double
End Interface

Public Class RightTriangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a right triangle. 
        Return 0.5 * (X * Y)
    End Function
End Class

Public Class RectangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a rectangle. 
        Return X * Y
    End Function
End Class

참고 항목

작업

방법: 인터페이스 만들기 및 구현

개념

상속 기반 다형성