Understanding OOP Concepts: Encapsulation

Last modified on June 26, 2020 56 sec read

In this article, we’re going to learn about Encapsulation. I hope you’ll get the basic idea. Let’s get started:

Table of Contents

  1. What is Encapsulation
  2. Example in Java
  3. Advantages of Encapsulation

What is Encapsulation

Encapsulation a mechanism of wrapping data together into a single unit. Using Encapsulation, we mainly hide “sensitive” data from users. For example, a capsule that is mixed of several medicines.

To achieve Encapsulation:

  • Declare properties/attributes as private.
  • Use get and set methods to access and update the value of a private variables/properties.

Example in Java

Let’s see an example of Encapsulation:

public class Person {
  private String name; // private access

  // set
  public void setName(String newName) {
    this.name = newName;
  }

  // get
  public String getName() {
    return name;
  }
}

We’ve defined name property as private. So, we’re unable to access this variable from outside of the class.

public class AnotherClass {
  public static void main(String[] args) {

    Person personObject = new Person();
    personObject.name = "Obydul";  // will show error
    System.out.println(personObject.name); // will show error

  }
}

We’ve to use setter & getter methods to access or update values like this:

public class AnotherClass {
  public static void main(String[] args) {

    Person personObject = new Person();
    personObject.setName("Obydul"); // set value
    System.out.println(personObject.getName()); // get value

  }
}

Advantages of Encapsulation

Let’s see some advantages of Encapsulation:

  • Increased security of data by hiding important data.
  • It provides the control of class attributes and methods.
  • The attributes/variables of a class can be made read-only or write-only.
  • Encapsulation is better for unit testing.
  • It improves maintainability, flexibility and re-usability. Since the implementation is purely hidden for outside classes.

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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