Encapsulation is one of the four fundamental concepts of object-oriented programming (OOP), along with inheritance, abstraction, and polymorphism. It refers to the bundling of data (variables) and methods (functions) into a single unit called a class. Encapsulation helps protect the integrity of the data by restricting direct access to some of the object's components and only allowing it through methods.
In practice, encapsulation is implemented using access specifiers like private, protected, and public in programming languages like Java, C++, and C#. These specifiers control the visibility of class members. For example:
class Rectangle { private: int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getArea() { return width * height; } };In the above example, the width and height variables are encapsulated within the Rectangle class, and their direct access is restricted. They can only be modified or accessed through the class's methods.