Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'make two instances of different kinds of objects
Dim objOfOneType As New Car("Dodge Stratus", 2002, Color.Blue)
Dim objOfAnotherType As New Person("Ed", 27)
'now cast the specific type to the interface it implements
Dim generic As IGenericName = objOfOneType
'run interface members regardless of what they are actually called in the class itself
generic.Display() 'will show "Dodge Stratus" in msgbox
'now for the other object
generic = objOfAnotherType
generic.Display() 'will show "Ed Marquez" in msgbox
'See how both can be used as IGenericName even though they are actually of other types.
'This could also be useful with method as you can have IGenericName as the parameter type
'then anything that implements it regardless of actual type can be passed in.
'This is the basics of polymorphic behavior, since the types can polymorph or change into other types.
End Sub
'example interface provides a required structure
Public Interface IGenericName
Property Name() As String
Sub Display()
End Interface
Public Class Car
Implements IGenericName
Private _Make As String = String.Empty
Private _Year As Integer = 2000
Private _Color As Color = Color.Blue
Public Property Make() As String Implements IGenericName.Name
Get
Return _Make
End Get
Set(ByVal Value As String)
_Make = Value
End Set
End Property
Public Property Year() As Integer
Get
Return _Year
End Get
Set(ByVal Value As Integer)
_Year = Value
End Set
End Property
Public Property Color() As Color
Get
Return _Color
End Get
Set(ByVal Value As Color)
_Color = Value
End Set
End Property
Public Sub ShowMake() Implements IGenericName.Display
MsgBox(Me.Make, , "Car")
End Sub
Public Sub New(ByVal make As String, ByVal year As Integer, ByVal color As Color)
Me.Make = make
Me.Year = year
Me.Color = color
End Sub
End Class
Public Class Person
Implements IGenericName
Private _Name As String = String.Empty
Private _Age As Integer = 25
Public Property Name() As String Implements IGenericName.Name
Get
Return _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal Value As Integer)
_Age = Value
End Set
End Property
Public Sub SayName() Implements IGenericName.Display
MsgBox(Me.Name, , "Person")
End Sub
Public Sub New(ByVal name As String, ByVal age As Integer)
Me.Name = name
Me.Age = age
End Sub
End Class