What is encapsulation?

Encapsulation means:

  • That member variables should be defined as private.
  • So that they cannot be directly accessed outside of the class.
  • They should only be accessed through their accessor methods.

Example - The Time Class

Yousuf has created the Time class shown below:

public class Time
{
    // member variables - defined as private so that they can not be directly accessed
    // outside of the class.
    private int hours;
    private int minutes;
    private int seconds;
}

Because Yousuf has correctly set the member variables as private. He must create accessor methods.

Accessor Methods

Accessor methods are often called "get/set" methods because they get or set a member variable. It is conventional to name them get (or set) followed by the variable name.

Here are the accessor methods to get and set the variable hours:

// accessor methods to set the member variable: hours
public void SetHours(int h)
{
    hours = h;
}

// accessor methods to set the member variable: hours
public int GetHours()
{
    return hours;
}