Java OOPS - Encapsulation

Java OOPS - Encapsulation

Welcome to 3rd article of Java OOPs series, in this article we will learn about Encapsulation.
In the last article , we saw Data hiding i.e hiding internal data by making variables private, and Abstraction - hiding implementation details by using an interface or abstract classes.

Let's start with Encapsulation

Encapsulation is defined as the grouping of data variables and corresponding methods in a single unit.
It basically acts as a shield to protect data from outside classes.
So, we are making use of Data Hiding by making the variables private.
Also, we are hiding the implementation of public methods to the outside world using the abstraction concepts.
We can then say Encapsulation = Data Hiding + Abstraction
Any component which implements Data hiding and Abstraction can be said as an encapsulated component.
All Java classes are by default encapsulated.

class Student{
    //implementation of data hiding
    private String name;
    private int id;
    private int marks;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public int getMarks() {
        return marks;

    public void setMarks(int marks) {
        this.marks = marks;

Here, in the Student class, all the variables are hidden using data hiding. Getters and Setters are used to get and set each variable.

Tightly Encapsulated Class

If all the variables of a class are private then that class is called a Tightly Encapsulated Class.


So far in the series, we have completed Data Hiding, Abstraction, and Encapsulation.
In the next one, we will learn one of the important pillars of OOP which is Inheritance.
Thanks for reading this one.
If you find this helpful, do like it.
Any suggestions comment below.
Link to the first article of this series.