' A class without encapsulation:
Code:
Class A
Public Field As Integer
Public Function MethodA() As Integer
Return Field + 1
End Function
End Class
The class above exposes its field directly to the user so it can be accessed from anywhere.
Code:
Class B
Private _Field As Integer
Private Function MethodB() As Integer
Return _Field + 1
End Function
Public Property Field As Integer
Get
Return _Field
End Get
Set(ByVal value As Integer)
_Field = value
End Set
End Property
Public ReadOnly Property Result As Integer
Get
Return MethodB
End Get
End Property
End Class
The second method encapsulates a private field which can be accesses only through a public property and you can perform validation in the 'Set' block. Also it encapsulates a 'business logic' method (MethodB) and only returns result through the readonly property. Using this technique you can protect your private members from any outside interference.