I’ve been learning C# over the past while, and as a result, I’ve been learning a lot about Object Oriented Programming concepts. I have a rather good understanding of classes and inheritance and am about to learn about polymorphism, but one concept I currently can’t wrap my head around is encapsulation. I just can’t understand what it does or why it’s even used in any sense. Any help would be appreciated, because I’d rather move forward having a good understanding of every c# concept I’ve touched on so far before moving on to new things.
In: Other
Encapsulation means designing a simple interface to hide the underlying complexity of a system. Think of encapsulation like a post on this subreddit. You take something complex and make it more simple so it’s easier to understand, and digest.
The main reason we bother with it is so that you can do 3 things.
* More easily understand (or control) the system you have encapsulated
* Build interesting stuff on top of that system without much effort
* Replace encapsulated components with different components as long as they use the same simple interface or encapsulation.
A city has a water and sewer system that winds its way through that city under the ground. It has inflows of water, reservoirs, pressure controls. There is a billing system and customers and people who control the quality and everything. But at your home there is simply a main water line (input), a water meter, and a main sewer line (output). All that complexity is simplified and standardized so that every plumber can think of a house in those simpler terms. A plumber does not need to know the full workings of one particular city’s water system in depth to work on a house. That leaves more room in their heads to think about the best way to lay out pipes in a home and it also allows their skills to work across the country in different cities.
So then the plumber lays the pipes for a house and builds it all to code. He does this on top of the simple encapsulation of the water main, the water meter, and the sewer line. But the plumber also uses encapsulation for all the pipes he has laid in the home. The faucets and showers and toilets are the simple interface for the home’s plumbing network. And the residents of the home use this simple interface.
But some houses are in cities that don’t have sewer systems. In that case, you can install a septic tank and connect it to the main sewer line of a home. They both use the same simple interface and therefore thanks to encapsulation you can interchange them. Same goes for the water main. If you had a well, a water pump and some filters/purifiers, you could hook that into your water main line for water input.
Latest Answers