Advanced Java/Encapsulation

Encapsulation is a procedure to allow access to internal class variables through methods.

Example:

While encapsulation may have a performance hit compared to direct access, its advantage is that it helps keep code clean and minimizes issues caused by arbitrary modification of internal variables. The example shown above keeps the  field private, and allows accessing its value from the   method and changing it from    While this example only shows a bridge to the private variable, it is possible to adjust the encapsulating methods to ensure other constraints get met (such as keeping value within 0 to 100) or to modify other fields as necessary.

This concept is related to factory classes or singleton classes, where the constructor is hidden from public usage but is encapsulated by another method.