Encapsulation

Perhaps the most important of the object-oriented concepts is that of encapsulation. Encapsulation is the idea that an object should totally separate its interface from its implementation. All the data and implementation code for an object should be entirely hidden behind its interface. This is the concept of an object as a black box.

The idea is that you can create an interface (by creating public methods in a class) and, as long as that interface remains consistent, the application can interact with your objects. This remains true even if you entirely rewrite the code within a given method. The interface is independent of the implementation.

Encapsulation enables you to hide the internal implementation details of a class. For example, the algorithm you use to find prime numbers might be proprietary. You can expose a simple API to the end user but hide all of the logic used in your algorithm by encapsulating it within your class.

This means that an object should completely contain any data it requires and should contain all the code required to manipulate that data. Programs should interact with an object through an interface, using the properties and methods of the object. Client code should never work directly with the data owned by the object.

Visual Basic classes hide their internal data and code, providing a well-established interface of properties and methods with the outside world. As was discussed during much of this chapter, you can change not only how a property or method is implemented but even where it is implemented within a class hierarchy. So long as you not changed the interface of the class, your working client program has no idea that you have switched from one implementation to the other.

The goal is to be able to totally change an implementation without any change of behavior visible to the client code. This is the essence of encapsulation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset