Advanced Java/Encapsulation

From Wikiversity
Jump to: navigation, search

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

Example:

public class Example
{
    private int value;

    public int getValue()
    {
        return value;
    }

    public void setValue(int param)
    {
        value=param;
    }
}

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 value field private, and allows accessing its value from the getValue() method and changing it from setValue() 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.