Interfaces in Visual Basic .NET
In this article, I will explain you about Interfaces and their implementation in Visual Basic .NET.
In this article, I will explain you about Interfaces and their implementation in Visual Basic .NET.
Interfaces
Interfaces define what is referred to as a contract. Literally, an interface is a type that contain methods, properties and events that classes can implement. Interfaces also provide another way of implementing polymorphism. We leave it to the class to implement those methods which are specify in an interface. With the help of an interfaces we can achieve multiple inheritance which is not supported by Visual Basic .NET. Visual Basic .NET introduces the Interface statement, which allows you to define true interfaces as distinct entities from classes, and to implement them with an improved version of the Implements keyword.
The following code show you the implementation of Interfaces:
Imports System.Console
Module Module1
Sub Main()
Dim FirstObj As New First()
Dim SecondObj As New Second()
'creating objects of class First and Second
FirstObj.Add()
FirstObj.Multiply()
SecondObj.Add()
SecondObj.Multiply()
'accessing the methods from classes as specified in the interface
Read()
End Sub
End Module
Public Interface Calculation
'creating an Interface named Calculation
Sub Add()
Function Multiply() As Double
'specifying two methods in an interface
End Interface
Public Class First
Implements Calculation
'implementing interface in class First
Public A As Double = 24
Public B As Double = 24.34
Sub Add() Implements Calculation.Add
'implementing the method specified in interface
WriteLine("Sum of A+B is" & A + B)
Read()
End Sub
Public Function Multiply() As Double Implements Calculation.Multiply
'implementing the method specified in interface
WriteLine("Multiple of A*B is" & A * B)
Read()
End Function
End Class
Public Class Second
Implements Calculation
'implementing the interface in class Second
Public C As Double = 40
Public D As Double = 64.34
Sub Add() Implements Calculation.Add
WriteLine("Sum of C+D is" & C + D)
Read()
End Sub
Public Function Multiply() As Double Implements Calculation.Multiply
WriteLine("Welcome to Interface")
Read()
End Function
End Class
The output of the above code is:
Summary
Hope this article help you to Understand Interfaces and their implementation in Visual Basic.