Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

Encapsulation in Java

Encapsulation is one of the four fundamental object-oriented programming/OOP concepts. These four fundamental OOP concepts are encapsulation, inheritance, abstraction, and polymorphism. This article focuses on encapsulation in the context of Java.

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Amazon Coding Interview Questions, Facebook Coding Interview Questions, and Google Coding Interview Questions for specific insights and guidance on Coding interview preparation.

Having trained over 11,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll learn:

  • What Is Encapsulation in Java?
  • How to Achieve Data Encapsulation in Java?
  • Advantages of Encapsulation in Java
  • Encapsulation in Java With Examples
  • Abstraction vs. Encapsulation in Java
  • FAQs on Encapsulation in Java

What Is Encapsulation in Java?

Encapsulation in Java refers to wrapping the data, variables, methods acting on the data, and code together into a single unit. Encapsulation hides the class variables from other classes. These class variables can be accessed only through the methods of their current class, leading to data hiding. 

To create a fully encapsulated class in Java, we need to make all the data members of the class private. We then use setter methods to set and getter methods to get the data in the class. An example of a fully encapsulated class is the Java Bean class.

Recommended Reading: Overriding in Java

How to Achieve Data Encapsulation in Java?

To achieve data encapsulation in Java, we need to:

  1. Declare the class variables as private using access specifiers.
  2. Create public setter and getter methods for the modification and viewing of the variable values, respectively.

Advantages of Encapsulation in Java

Some of the advantages of using encapsulation in Java include:

  • Since other classes can’t access data in the private data members of a class, it is a means to achieve data hiding in Java.
  • It is easy to unit test an encapsulated class. 
  • It is quick and easy to create an encapsulated class in Java using standard IDEs that facilitate the generation of the getter and setter methods.
  • If we give only a setter or getter method, we can make the entire class read-only or write-only. We can also skip the getter or setter methods.
  • We can make class fields read-only or write-only.
  • A class can control what we can store in its fields. 
  • It gives us control over the data. We can write the logic inside the setter method to limit what kind of values can be stored in a variable, including data type, positive or negative, within what range, etc. 

Encapsulation in Java With Examples

Let’s look at some examples to understand the concept of encapsulation in Java better.

1. Example of a Fully Encapsulated Class

The class below has all the data members as private, making it a fully encapsulated class. We also have getter and setter methods for reading and writing:


class LRU_cache
// A Java class which is a fully encapsulated class. It has a private data member, and getter and setter methods.  
public class fullyEncapsulated {
    // Private data member  
    private String privateVariable;

    // Getter method for privateVariable  
    public String getPrivateVariable() {
        return privateVariable;
    }
    // Setter method for privateVariable   
    public void setPrivateVariable(String privateVariable) {
        this.privateVariable = privateVariable;
    }
}


Using the fullyEncapsulated class (stored with the file name fullyEncapsulated.java) in the following manner: 

File-name: useFullyEncapsulated.java


class useFullyEncapsulated {

    public static void main(String[] args) {
        // Creating instance of the encapsulated class  
        fullyEncapsulated fullyEncapsulatedObject = new fullyEncapsulated();
        // Setting value in the name member  
        fullyEncapsulatedObject.setPrivateVariable("IK");
        // Getting value of the name member  
        System.out.println(fullyEncapsulatedObject.getPrivateVariable());
    }
}


2. Read-Only Class

The following is an example of a read-only class. It only has the getter method, no setter method. Here, we can only read, not modify the data member values or properties of the class:


// A Java class which is a fully encapsulated class.  It has a private data member, and only a getter method.  

public class fullyEncapsulated {
    // Private data member  
    private String privateVariable;

    // Getter method for privateVariable  
    public String getPrivateVariable() {
        return privateVariable;
    }
}


Write-Only Class


// A Java class which is a fully encapsulated class.  It has a private data member and only a setter method.  
public class fullyEncapsulated {
    // Private data member  
    private String privateVariable;

    // Setter method for privateVariable   
    public void setPrivateVariable(String privateVariable) {
        this.privateVariable = privateVariable;
    }
}

The following is an example of a write-only class. It only has the setter method, no getter method. Here, we can only modify, not access, or read the data member values or properties of the class:

Abstraction vs. Encapsulation in Java

Abstraction is the mechanism of hiding unnecessary information to avoid misuse of code, highly coupled code, and confusion leading to more errors. 

Encapsulation is the mechanism of hiding data in a single entity/unit with a method that protects the information from the outside, even when giving get/set access. 

Abstract classes are implemented using abstract class and interfaces, while encapsulation involves using access modifiers like private along with getter and setter methods to be done.

Keep brushing up on your Java basics; visit the Learn page for more.

FAQs on Encapsulation in Java

Q1. How can the concept of encapsulation be achieved in a program?

To achieve data encapsulation in Java, we need to declare the class variables as private using access specifiers. We also need to create public setter and getter methods for modifying and viewing the variable values, respectively.

Q2. Which access modifier is used for encapsulation in Java?

The access modifier “private” is used for encapsulation in Java.

Q3. Why is encapsulation important in Java?

Encapsulation hides implementation details from the clients, giving them just the smooth experience they need. It hides data that is irrelevant to other classes, making it less likely for them to misuse it and cause confusion/errors. It provides more control over the code, coupling, and decision involving which behavior to expose.

Q4. What are the benefits of encapsulation in Java?

Data hiding, easy unit testing, quick and easy to create using IDEs, making the class fields or the entire class read-only or write-only, and increasing control over code are some of the advantages of encapsulation in Java.

Q5. Are encapsulation and data hiding the same?

No. In data hiding, the data can only be defined as private, whereas the data can be public or private in data encapsulation. Encapsulation is a sub-process in data hiding. And data hiding is a process and technique both in itself.

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Hosted By
Ryan Valles
Founder, Interview Kickstart
Our tried & tested strategy for cracking interviews
How FAANG hiring process works
The 4 areas you must prepare for
How you can accelerate your learnings

Recommended Posts

All Posts