VB.NET Encapsulation

  • Encapsulation is simple concept which prevents the access to data that is not essential.
  • It is a process of binding the variable and methods together required by an object in a single unit that is class.
  • Encapsulation is a technique of hiding internal details of a class to prevent data to be accessed from the outside world.
  • When we combine the state and behavior into a container then it is called as encapsulation.
  • In VB.NET, encapsulation is achieved through class concept.
  • We can understand this concept using following diagram:
  • encapsulation

  • The most popular and real time example of the encapsulation is capsule as shown above.

Advantage of Encapsulation

  • It provides data security.
  • It provides the abstraction between objects and its clients.
  • It provides the security from the unwanted access.
  • The example of the encapsulation is as follows:
Module Module1

Class Sum
Private a, b As Integer
Public Sub addition()
Console.WriteLine("enter a and b :")
a = Console.ReadLine()
b = Console.ReadLine()
Console.WriteLine("Sum : {0}", (a + b))
End Sub
End Class

Sub Main()
Dim s As Sum = New Sum()
End Sub

End Module

In the above example, all the data members and functions are declared and defined or bind inside the class. Here we cannot access the class members directly. Here we can only access the elements of class using the object of the class.

The output is as follows: