Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

This chapter is from the book

Encapsulation in VB.NET

Encapsulation is the exposure of properties and methods of an object while hiding the actual implementation from the outside world. In other words, the object is treated as a black box—developers who use the object should have no need to understand how it actually works.

Encapsulation allows developers to build objects that can be changed without affecting the client code that uses them. The key is that the interface of the object, the set of exposed properties and methods of the object, doesn't change even if the internal implementation does. VB has supported encapsulation since version 4.0.

Lets take a look at two trivial examples of a Person class. Listings 3.5 and 3.6 and implement the same functionality in two different ways.

Listing 3.5 Person Class Implementation #1

Public Class Person
    Private m_sFirstName as String
  Private m_sLastName as String
  Public Property FirstName() as String
    Get
      FirstName = m_sFirstName
    End Get
    Set(ByVal Value as String)
      m_sFirstName = Value
    End Set
  End Property
  Public Property LastName() as String
    Get
      LastName = m_sLastName
    End Get
    Set(ByVal Value as String)
      m_sLastName = Value
    End Set
  End Property
  ReadOnly Property FullName() as String
    Get
      FullName = m_sLastName & ", " & m_sFirstName
    End Get
  End Property
End Class

Listing 3.6 Person Class Implementation #2

Public Class Person
    Private m_sFirstName as String
  Private m_sLastName as String
  Private m_sFullName as String
  Public Property FirstName() as String
    Get
      FirstName = m_sFirstName
    End Get
    Set(ByVal Value as String)
      m_sFirstName = Value
      m_sFullName = m_sLastName & ", " & m_sFirstName
    End Set
  End Property
  Public Property LastName() as String
    Get
      LastName = m_sLastName
    End Get
    Set(ByVal Value as String)
      m_sLastName = Value
      m_sFullName = m_sLastName & ", " & m_sFirstName
    End Set
  End Property
  ReadOnly Property FullName() as String
    Get
      FullName = m_sFirstName
    End Get
  End Property
End Class

This illustrates how the internal implementation of the classes is different but the external interface encapsulates how the class works internally. That is the goal of encapsulation: to allow a developer to transparently use different implementations of the same object.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus