Programs

What is Encapsulation in OOPS [Explained With Examples]

Object-oriented programming languages (OOPs) are built around objects and classes. While a class is an abstract blueprint for building concrete objects, an object is a data field with unique attributes and behavior. OOP class dictates how an object will behave and what it contains. In other words, an object is an instance of a class with properties and methods for making a particular type of data useful. Thus, when we send a message to an object, we ask the object to execute or invoke one of its methods defined in the class. 

Encapsulation in OOPs is one of the core properties that makes object-oriented programming an efficient programming paradigm. Encapsulation – together with inheritance, abstraction, and polymorphism – is referred to as the four pillars of object-oriented programming. 

In this article, we’ll focus on encapsulation in C++ and Java.

What is Encapsulation?

Encapsulation in OOPs is the concept of binding fields (object state) and methods (behavior) together as a single unit. Programming languages such as Java use encapsulation in the form of classes. A class allows programmers to create objects with variables (data) and behaviors (methods or functions). Since a class consists of data and methods packed into a single unit, it is an example of encapsulation.

Encapsulation in OOPs may also mean restricting direct access to certain components of an object so that users can’t access the state values for all variables of a particular object. Therefore, encapsulation can be used to hide data members and functions associated with an instantiated class or object. Encapsulation is analogous to a capsule where the mixture of medicines inside the pill represents the data and methods while the hard outer shell could be thought of as the class.

Real-time Examples of Encapsulation

Here are two real-time analogies to understand encapsulation better.

#1 Example

In a large organization, there are several departments like sales, accounts, production, etc., each with its own responsibilities and functions. Now, consider a situation where a member of the accounts section needs all the sales data of a particular month. In such a case, the accounts official cannot access the sales data directly. Instead, they have to contact some member of the sales department and request them to furnish the required data. Thus, the situation here is similar to encapsulation, where the sales data and the officials who can directly access them are wrapped under a single domain, “Sales Department.”

#2 Example

When we log in to our email accounts, many back-end processes take place over which we have no control. The password we enter is retrieved in an encrypted form and verified, after which we get access to our account. Thus, we have no way of knowing how our password gets verified, keeping our account safe from misuse. It is another classic real-time analogy of encapsulation where users have restricted access to certain features.

With those real-time examples in mind, let’s see how encapsulation looks like in Java and C++, two of the most popular object-oriented programming languages.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Encapsulation in Java

The idea behind encapsulation in OOPs is to keep the implementation details hidden from the user. If a data member is private, it can only be accessed within the same class, and no outside class can access the private data members (variables). 

In Java, encapsulation can be implemented using private access specifiers on all the variables within a class so that no outside class can access them. However, if we set up public get and set methods to access and update the private data fields, outside classes can access the private data fields via public methods. As a result, only public methods can access the data, hiding the private fields and their implementation for outside classes. This is why encapsulation is also often referred to as data hiding.

So, to achieve encapsulation in Java, we must declare class attributes/variables private and declare public set and get methods to access and update the private variables’ values.

Following is a Java program to illustrate encapsulation:

class DemoEncapsulation {

  private String course;

  public String getCourse() {

    return course;

  }

  public void setCourse(String c) {

    this.course = c;

  }

}

public class Encapsulation {

  public static void main(String[] args) {

    DemoEncapsulation de = new DemoEncapsulation();

    de.setCourse(“Computer Science”);

    System.out.println(de.getCourse());

    //System.out.println(DemoEncapsulation.course);

  }

}

Output:

Computer Science

 

In the above example, the data field course is private and cannot be accessed directly. It is a hidden data field that can only be accessed via public methods.

 

Encapsulation in C++

Similar to Java, encapsulation in C++ can be implemented using class and access specifiers. The Java example shows that access specifiers play a critical role in encapsulation. In C++, implementation of encapsulation has two steps: first, labeling data members as private using the private access specifier, and second, tagging the member function that manipulates data members as public. 

Following is a C++ program illustrating encapsulation:

class EncapsulationExample

{

private:

// data hidden from outside world

int a;

public:

// function to set value of

// variable a

void set(int x)

{

a =x;

}

// function to return value of

// variable a

int get()

{

return a;

}

};

 

// main function

int main()

{

EncapsulationExample obj;

obj.set(4);

cout<<obj.get();

return 0;

}

Output:

4

In the above program, the variable a has been made private. It can be accessed and manipulated using only the functions get() and set()present inside the class. Therefore, the variable a and functions get() and set()are wrapped together, which is nothing but what encapsulation is all about.

With that example of encapsulation in C++, we end our discussion on encapsulation in OOPs.

Conclusion

Encapsulation is a fundamental concept in object-oriented programming. It essentially means binding variables and methods together into a single unit and preventing them from being accessed by other classes. 

Every Java class that we create is an example of encapsulation because the class binds methods and variables together. We write everything within the class that remains hidden from outside classes. When we implement encapsulation, we declare the fields in the class as private to prevent other classes from accessing them directly. However, the encapsulated data can only be accessed using public get() and set() methods. As a result, encapsulation confers several advantages: data security, code flexibility, and application maintainability.

Way Forward

If you are looking to enhance your Java knowledge and master the in-demand software development skills, check out upGrad’s Master of Science in Computer Science Program from Liverpool John Moores University. The engaging and rigorous online program is specially designed for working professionals who wish to develop practical knowledge and skills to accelerate entry into computer science careers.

Program Highlights:

  • Master’s degree from LJMU and Executive PGP from IIIT Bangalore
  • Certification in Data Science & Machine Learning
  • 500+ hours of content with 30+ case studies and projects
  • Comprehensive coverage of 30+ tools, including Java
  • 360-degree learning support
  • Industry and peer networking

upGrad’s immersive learning programs have impacted over 500,000 working professionals worldwide. Join the 40,000+ learner base and give your career a successful launch!

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Best Data Science Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×