Tuesday 7 January 2014

Encapsulation & Abstraction

Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.

Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).

It is used to display only necessary and essential features of an object to ouside the world.Means displaying what is necessary and encapsulate the unnecessary things to outside the world.Hiding can be achieved by using "private" access modifiers.

Encapsulation enables a class to hide the internal implementation details and to protect itself from unwanted changes that would result in an invalid or inconsistent internal state. For that reason, encapsulation is also sometimes referred to as data hiding.

As an example of encapsulation at work, think about your car. You start your car in the morning by inserting a key and turning it (or simply pushing a button, in some cases). The details of what happens when you turn the key (or push the button) that actually causes the engine to start running are hidden from you. You don't need to know about them to start the car. It also means you can't influence or change the internal state of the engine except by turning the ignition key.

By hiding the internal details and data, you create a public interface or abstraction representing the external details of a class. This abstraction describes what actions the class can perform and what information the class makes publicly available. As long as the public interface does not change, the internal details can change in any way required without having an adverse affect on other classes or code that depends on it.

By keeping the public interface of a class small and by providing a high degree of fidelity between your class and the real-world object it represents, you help ensure that your class will be familiar to other programmers who need to use it.

Let's look at our car example again. By encapsulating the details of what happens when you start your car and providing an action, StartCar, and information, such as IsCarStarted, we have defined a public interface, thereby creating an abstraction (or at least a partial abstraction, because cars do much more than just start) of a car.

No comments:

Post a Comment