I understand the concept of interfaces, however I often find it difficult to find practical examples of how to use them. I have produced the following code:
Public MustInherit Class Deletion2
Implements DeletionInterface2
Public MustOverride Function Delete() As String Implements DeletionInterface2.Delete
Public Function CheckDate() As Boolean Implements DeletionInterface2.CheckDate
Return True
End Function
End Class
Public Class System1Delete
Inherits Deletion2
Implements DeletionInterface2
Overrides Function Delete() As String
Return "System 1 Deleted"
End Function
End Class
Public Class System2Delete
Inherits Deletion2
Implements DeletionInterface2
Overrides Function Delete() As String
Return "System 2 Deleted"
End Function
End Class
Public Interface DeletionInterface2
Function CheckDate() As Boolean
Function Delete() As String
End Interface
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IDeletion As DeletionInterface2
IDeletion = New System1Delete
IDeletion.CheckDate()
IDeletion.Delete()
IDeletion = Nothing
IDeletion = New System2Delete
IDeletion.CheckDate()
IDeletion.Delete()
IDeletion = Nothing
End Sub
In the example above (in page load) I have used a reference to an interface to create an instance of an object, but I do not understand the true benefit of this.
The benefit of using an abstraction like an interface (or a
MustInheritclass) is that you can treat any object that implements the interface the same exact way.For example, the
System.Datanamespace uses many such abstraction, meaning that implementing the different data providers is easier and since the core is using these abstractions, it doesn’t need to change as new implementations are added (things about all the different providers, built in and third party – SQL Server, Oracle, PostGresSQL, MySQL etc…).