Understanding OOP Concepts: Encapsulation
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
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.
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)