Encapsulation is one of the four fundamental OOP concepts. It is the inclusion within a program object of all the resources needed for the object to properly function on its own - basically, the methods and the data. The object has its public interface and other objects adhere to these interface to use the object without having to be concerned with how the object internally implements it. The idea is "don't tell me how you do it; just do it".
To understand importance of encapsulation you need to understand such term as information hiding in computer science. Information hiding is the principle of segregation and isolation of the design decisions that are most likely to change from program code user, thus protecting him from extensive modification if the design decision is changed. Such protection involves providing a constant interface which protects the remainder of the program from the implementation (the details that are most likely to change). Written another way, information hiding is the ability to prevent certain aspects of a class or other software code from being accessible to its users, using programming language features like private variables.
But the key is not only to hide data from users, encapsulation doesn't mean that you shouldn't expose any data at all. The other important point is to hide the internals of the object to protect its integrity by preventing users from setting the internal data of the object into an invalid or inconsistent state. Encapsulation is not only about hiding complexity, but also about exposing needed part of implementation complexity in a fail-safe manner, using programming language features like getters and setters for fields.
So, importance of encapsulation explained by need to produce cohesive pieces of code (classes) that solve given problems once and for all, so that programmers can use those classes without having to learn about the intricate details of the implementations.
Most languages implement encapsulation via fields access modifiers of class members. C# also has construct known as properties, which exposes data via getters and setters, but hides details about how this data contructed and stored and also checks incoming data to prevent corruption of inner state of object.
- Encapsulation is one of the four fundamental OOP principles.
- Encapsulation is about implementation hiding: hide information which user doesn't need to know to work with code, show needed information but in manner which doesn't allow user to corrupt it.
- Encapsulation achieved in most languages via access modifiers and getters/setters for fields.