sunshine



What is Encapsulation

Encapsulation is considered as the first pillar of Object Oriented Programming(OOP).

Encapsulation is the process of hiding complexities of an object from its consumers.Encapsulation hides all the secrets of an object as well as implementation details.

The object exposes its capabilities through an interface to the consumer. How exactly the object implement those capabilities are not the business of consumers. Consider the example of a an automobile. A driver can control the direction of the car using the steering wheel. Control the speed with gas pedal and gears unless its automatic. And most importantly stop the car using the break. Gas pedal, steering wheel, gear stick and brakes are the interface. How they function is encapsulated from the driver.Look at the CarEngine class below.

CarEngine

{

  private int Cylinders ;

  public void Start() { ......}

  public void Stop(){.....}

  private bool FillTheChambersWithGas() {....}

  private bool StartTheSparkPlug(){....}

}

The consumer of the CarEngine, which is a car, would use only Start() and Stop() methods. All others methods and the internal implementation are not the concern of the consumer here. Please note that encapsulation does not mean that you cannot see the private methods. You can see the code. But when an object is created out of this class, it can access only public methods.

For example in C#

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

will spawn two threads and execute the function DoSomeWork. Parallel class encapsulate all the details of how threads are implemented, how thread pools are implemented etc fro you.

So how does it help?

Encapsulation helps to implement objects which got independent, specilized and fine grained responsibility. You can design your software anyway you want to. There is more than one way to skin a cat. If you follow OOP, you can design code which is scalable, maintainable and extensible. OOP is discipline which will help you do that. Encapsulation is a big part of that discipline which works in hand with another concept call abstraction helps to design better software.

Encapsulation may be mistaken for abstraction. But they are two different vital concepts. Abstraction is the observable behavior of an object. Encapsulation is about implementing that behavior.

So in the above example, the observable behaviors are Start and Stop. We encapsulated all other stuff with proper access specifiers.

We offer one on one C# training,SQL training,WCF training,WPF training,WinForms training, MVC training, ASP.NET training, Ajax & Javascript training. Please see the contacts page

Grady Booche's Object Oriented Analysis and Design With Applications is great book on OOP.