Encapsulation is a mechanism to hide actual implementation from outside , by using private access specifier for methods and properties in a class. Example is TV Remote – you don’t know how it works internally.
So, this is basically a concept of hiding the code [show only essential data of object – It is abstraction]. Actually, Encapsulation is used hide the member function, variable, etc. to the outside world.
So, Encapsulation is a way of encapsulating the data [wrapping the data] into a single unit called class. Through encapsulation, we can protect our data.
Why Encapsulation
If you think, there is some code that should not be exposed to outside code. There you can use Access Modifier to encapsulate the data.
Real Time Example
Let us take an example of TV, When we watch TV, we need only TV and Remote. To use Remote Key we can manage everything of a TV. There is no one interesting in knowing what is happening when we press the Remote button.
Using the Remote, we can increase the Volume, change the channel, and change the color of Screen, etc. But we never think how it is happening in the backend.
Actually in Remote System, on every key press there is some logic behind this. That is not useful for everyone. Remote encapsulate the logic and when we press the key, it performs the action. So, this is a real time example of Encapsulation. Not only Remote, you can see lot of devices around you which use Encapsulation like your phone, your car, etc.
- classTV
- {
- //background method to increase the volume of TV on key press
- privatevoidVolumePlus()
- {
- Console.WriteLine(“Volumen Plus”);
- }
- //background method to decrease the volume of TV on key press
- privatevoidVolumeMinus()
- {
- Console.WriteLine(“Volumen Minus”);
- }
- //color change of Color Tube on key press
- privatevoidColorTube()
- {
- Console.WriteLine(“Color Tube of a Television”);
- }
- publicvoidTVKeys()
- {
- Console.WriteLine(“Television Keys”);
- }
- publicvoidTVRemote() {
- Console.WriteLine(“Television Remote”);
- }
- publicvoidTVScreen() {
- Console.WriteLine(“Television Screen”);
- }
-
- }
Above example will clear your doubts, you can see in above example some methods are private. It is because they will perform the logic on key press in background. We don’t need to know about this. But some are public, that will be accessible to us.