Encapsulation is the practice of hiding data inside a class and controlling how it is accessed.
Instead of allowing direct access to variables, you use properties to safely read and modify data.
Encapsulation protects your data from incorrect or unwanted changes.
Fields should usually be marked as private so they cannot be accessed directly from outside the class.
This forces users of the class to go through controlled methods or properties.
Properties provide a safe way to access private fields.
They allow you to control both reading (get) and writing (set) of data.
One of the biggest advantages of encapsulation is adding validation when setting values.
This prevents invalid data from being stored.
Here is a full example showing encapsulation working in a program.
Using public fields is not recommended because it allows unrestricted access.
Encapsulation provides control and prevents errors.
Encapsulation is a core concept in object-oriented programming and is widely used in real-world applications.
Create a BankAccount class with a private balance. Use a property to control deposits and prevent negative values.