Encapsulation means that developers can contain and hide information about an object, such as internal data structures and code. It isolates the internal complexity of an object's operation from the rest of the application.
For example, when you set the Caption property on a command button, you don't need to know how the string is stored. Visual Basic will help you do this by letting you declare properties and methods as private protected or public.
Why would you want to protect class members? Let's assume that certain properties of a class represented an object's state. If you couldn't prevent those properties from being accessed directly from outside the class, how could you ever guarantee the state of that object? If you protect the property, you could then create a custom method that would be used to assign values to that property. The method could contain validation code to ensure that the value is set properly. Since the property value is assigned in just one place, the code becomes much easier to debug and maintain. In the example below, "me" refers to a specific instance of a class.
Protected cName as string
Protected Function ChangeName(NewName)
Me.cName = NewName
End Function
Comments