Association in OOP with Visual Basic .NET

September 4, 2017

Association shows the relationship between classes

There are two types of Associations
1 Unary Association
2 Binary Association

1. Unary Association

Class A does not know about ClassB
Class B knows about ClassA

To indicate the Unary Association single head arrow is used as shown in the below figure

Now lets look at the following example
You can see the Person and Address relationship below. We call this relationship as has-a relationship since person has a address

So Person knows the address but address does not know anything about person

Now lets see how we can implement this Person and Address association in VB.NET

In Visual Studio, you can draw the UML diagram  as shown in the below figure

You can see that Person class has attribute for the Address Class

Address Class

Public Class Address
    Private m_number As String
    Private m_city As String
    Private m_state As String
    Private m_zip As String
    Public Property Zip() As String
        Get
            Return m_zip
        End Get
        Set(ByVal value As String)
            m_zip = value
        End Set
    End Property

    Public Property State() As String
        Get
            Return m_state
        End Get
        Set(ByVal value As String)
            m_state = value
        End Set
    End Property

    Public Property City() As String
        Get
            Return m_city
        End Get
        Set(ByVal value As String)
            m_city = value
        End Set
    End Property

    Public Property Number() As String
        Get
            Return m_number
        End Get
        Set(ByVal value As String)
            m_number = value
        End Set
    End Property

  


End Class

Person Class

Public Class Person
    Private m_address As Address
    Private m_name As String
    Public Property Name() As String
        Get
            Return m_name
        End Get
        Set(ByVal value As String)
            m_name = value
        End Set
    End Property

    Public Property Address() As Address
        Get
            Return m_address
        End Get
        Set(ByVal value As Address)
            m_address = value
        End Set
    End Property

End Class

In this example, Person class has Address attribute and it will show you the unary association

2. Binary Association

In Binary association, Class A knows Class B and Class B knows Class A

To indicate the Binary Association simple line is used as shown in the below figure

Now we can see the Teacher and Course relationship in the following UML diagram

Here, teacher knows the course and course knows the teacher

Now we will see how you can implement bi-directional association with VB.NET

Course Class

Public Class Course
    Dim m_teacher As Teacher

    Public Sub SomeMethod()

    End Sub
End Class

Teacher Class

Public Class Teacher
    Dim m_course As Course
    Public Sub SomeMethod()

    End Sub
End Class