Encapsulation protects the data and methods from external disturbances by restricting direct access to them.
Encapsulation is the process of enclosing data and operations into a class to provide them with a protective barrier.
Encapsulation binds data and procedures that alter them into a single unit to hide sensitive info from users.
Data member Encapsulation -
- By using access specifiers
- Involves making data members private inside a class.
- Still you can alter or obtain the value of a data member using the Setters and Getters methods. .
- Encapsulating Methods & Properties:
- We can hide the methods usage for internal implementation that should not be accessible to the public by utilizing method encapsulation.
- To prevent users from accessing such a method, it should be marked as private.
Class encapsulation
a mechanism that combines data and methods into a single unit called a class. Encapsulation in C# is like putting your things in a Capsule(class
Advantage
- Data Hiding: The user doesn't know the class's inner implementation.
- Flexibility: We can create class variables read-only or write-only as needed. Make variables read-only by using Get Accessor in the code. Set Accessor is all we need to create variables write-only.
- Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
- Testing: Encapsulated code is easy to test for unit testing.