Object-Oriented Programming


Encapsulation is accomplished when each object maintains a private state, inside a class. Other objects can not access this state directly, instead, they can only invoke a list of public functions.

The object manages its own state via these functions and no other class can alter it unless explicitly allowed. In order to communicate with the object, you will need to utilize the methods provided.

An example of a good encapsulation is to implement Getters/Setters

#include <iostream>  
using namespace std;  
class Employee {  
    // Private attribute  
    int salary;  
    // Setter  
    void setSalary(int s) {  
      salary = s;  
    // Getter  
    int getSalary() {  
      return salary;  
int main() {  
  Employee myObj;  
  cout << myObj.getSalary();  
  return 0;  

Explaining Encapsulation

If we want to apply encapsulation, we do so by encapsulating all “dog” logic into a Dog class. The “state” of the dog is in the private variables playful, hungry and energy and each of these variables has their respective fields. 

There is also a private method: bark(), The dog class can call this whenever it wants, but other classes cannot tell the dog when to bark Encapsulation

There are also public methods such as sleep(), play() and eat() that are available to other classes. Each of these functions modifies the internal state of the Dog class and may invoke bark(), when this happens the private state and public methods are bonded.