VB.NET Interfaces


The interface is a definition of a role, or you can say a group of abstract actions. It defines what sort of behavior a certain object must exhibit, without specifying how this behavior should be implemented. It can neither be directly instantiated as an object nor can data members be defined. So, an interface is nothing but a collection of method and property declarations.

  • An interface can declare only a group of related functionalities, it is the responsibility of the deriving class to implement that functionality.
  • An interface is defined with the Interface keyword.
  • An interface can contain declarations of methods, properties, indexers, and events, but it may not declare instance data, such as fields, auto-implemented properties, or property-like events.
  • Multiple inheritances is possible with the help of interfaces, but not with classes.

The following code shows how to define a simple interface.

Interface IShape
    Property X As Double
    Property Y As Double
    Sub Draw()
    Function CalculateArea() As Double
End Interface

It is like an abstract class because all the methods which are declared in the interface are abstract. It cannot have a method body and cannot be instantiated.

Implementing an interface is simply done by inheriting it and defining all the methods and properties declared by the interface as shown below.

Public Class Rectangle
    Implements IShape

    Public Property X As Double Implements IShape.X
    Public Property Y As Double Implements IShape.Y

    Public Sub New(ByVal xVal As Double, ByVal yVal As Double)
        X = xVal
        Y = yVal
    End Sub

    Public Function CalculateArea() As Double Implements IShape.CalculateArea
        Return X * Y
    End Function

    Public Sub Draw() Implements IShape.Draw
        Console.WriteLine("Draw rectangle of X = {0}, Y = {1}.", X, Y)
    End Sub

End Class

Although a class can inherit from one class only, it can implement any number of interfaces. To implement multiple interfaces, separate them with a comma.

Public Class Rectangle
    Implements IShape, IDrawable

Now we can create a Rectangle object and assign it to a variable of the IShape type.

Public Sub Example1()
    Dim rectangle As IShape = New Rectangle(5, 7)
    rectangle.Draw()
    Console.WriteLine("The area of the rectangle is " & rectangle.CalculateArea())
End Sub

Let's run the above code and you will see the following output.

Draw rectangle of X = 5, Y = 7.
The area of the rectangle is 35