Encapsulation Principle

Encapsulation is one of the 4 main OOP principles.

It protects the class data from access outside the class body.

Members that are supposed to be accessed only in the class are labeled with _ prefix.

Example of encapsulation

Result:

Explanation:

  • The private members (_model and _manifactureYear) are supposed to be accessed / modified by functions defined inside the class (in this case getters and setters).
  • Access outside the class body is done the get and set functions (model and manifactureYear).

Example of no encapsulation

Output:

All members are accessed outside the class body.