What is encapsulation in OOP?

Encapsulation in OOP Theory is the process to mask some properties and operations in the class that will become inaccessible from the exterior: these are only internal things and behaviours like a digestive system.

It's a compartmentalization.

Here is a short and reduced description of what access modifiers do in C#:

  • Public : fields (variables) and properties (variables encapsulation) and methods (functions and procedures) are visible and accessible by the class itslef, by its childs and by any other external classes.
  • Private : members (fields, properties and methods) are visible and accessible only by the class, not by its childs nor by any external class.
  • Protected : members are visible and accessible by the class and by its childs, but not by others classes.
  • Internal : members are visible and accessible by the class and by its childs and by any class that is in the same assembly (.exe and .dll), but not by a class from another assembly.

Here is a rule:

  • If childs classes can modify something it should be set as a protected field, and offer a public property (get) if available for external items.
  • If childs classes are not allowed to modify comething it should be set as a private field and offer :

- A propected property with only a getter if external items can't access it.

- A public property with only a getter if external items can access it.

Don't repeat a member with the same name else it will hide the parent and can cause polymorphism problems, unless knowing what is done.

Links

CC BY-SA 4.0 Original Post