Harold Serrano

View Original

The three types of encapsulation in OOP

Member Variable Encapsulation

In Object Oriented Programming, all data members should be declared as Private members of the Class. Any object wishing to modify/retrieve the value of a data member should use Setters or Getters functions. You most likely know this as Data Member Encapsulation. Here is an example of setters and getters declared in a Class:

class Circle {

private:
    //private data member
    int diameter;

public:
    //constructor
    Circle();
    ~Circle();

    //setter function
    void setDiameter(float uValue);
    //getter function
    float getDiameter();

};

However, data member encapsulation is not the only way to encapsulate data. You can also encapsulate Functions and Classes.

Function Encapsulation

Functions used only for internal implementation of your API must always be declared Private. For example, the following class represents a Circle:

class Circle {

private:
    //private data member
    int diameter;

    //private method
    void calculateCircumference();

public:
    //constructor
    Circle();
    ~Circle();

    //setter function
    void setDiameter(float uValue);
    //getter function
    float getDiameter();

};

We have a setter method which modifies the Diameter of a circle. It is evident that this method should be made Public since the user will provide this data. However, the method CalculateCircumference() should not be declared Public. The user should not have access to this method, and it should be declared as a Private method. Remember, always hide any function that does not need to be public.

Class Encapsulation

The same logic applies to classes used for internal implementations of your API. These classes should not be part of any public interface of an API. They should be hidden from your users and made Private. For example, your API may have a class which sets a particular gradient color to a circle depending on its position. If your user does not need access to this Gradient class, you should encapsulate it, in other words, you should declare it as a Private class as shown below:

class Circle {

private:
    //private data member
    int diameter;

    //private method
    void calculateCircumference();

    //private class
    class Gradient{

        public:

        Gradient();

        ~Gradient();

        void setGradient(float uValue);

    };

public:
    //constructor
    Circle();
    ~Circle();

    //setter function
    void setDiameter(float uValue);
    //getter function
    float getDiameter();
};

In summary, Object Programming provides three different ways to encapsulate data. You can encapsulate data members, methods, and classes. Hope this was helpful.