View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Encapsulation in Java with Example

By Pavan Vadapalli

Updated on Nov 14, 2022 | 7 min read | 6.4k views

Share:

Encapsulation in Java is the process of wrapping up data or all the variables and the code that’s acting on that data into one single unit or bundle. It can only be accessed through a member function that belongs to an individual class of its own in which it has been declared. This mechanism binds the code together with the data it manages. It also helps prevent the accessing of data by any code outside the shield. 

Encapsulation in Java is also known as a combination of data hiding and abstraction. The data in a particular class is hidden and abstracted from other classes. This goal is attained by making the members or variables of a class private. This process can be accomplished by declaring all the members and variables privately and writing public methods in the class. This results in “getting” and “setting” the value of each variable privately.

Check out our free courses to get an edge over the competition 

How Does Encapsulation in Java Work?

In Java, there are mainly two steps to implement data encapsulation:

  • The access modifier ‘private’ needs to be used to declare the class member variables. 
  • The public getter and setter methods need to be applied, respectively, to access these private member variables and change their values.

Here is a code depicting encapsulation in Java:

class EncapsulationDemo{

    private int ssn;

    private String cusName;

    private int cusAge;

    //Getter and Setter methods

    public int getCusSSN(){

        return ssn;

    }

    public String getCusName(){

        return cusName;

    }

    public int getcusAge(){

        returncusAge;

    }

    public void setcusAge(int newValue){

        CusAge = newValue;

    }

    public void setcusName(String newValue){

        CusName = newValue;

    }

    public void setcusSSN(int newValue){

        ssn = newValue;

    }

}

public class EncapsTest{

    public static void main(String args[]){

         EncapsulationDemo obj = new EncapsulationDemo();

         obj.setcusName(“Erica”);

         obj.setcusAge(24);

         obj.setcusSSN(001122);

         System.out.println(“Customer Name: ” + obj.getCusName());

         System.out.println(“Customer SSN: ” + obj.getCusSSN());

         System.out.println(“Customer Age: ” + obj.getCusAge());

    } 

}

Check out upGrad’s Java Bootcamp

Output

Customer Name: Erica

Customer SSN: 001122

Customer Age: 24

Types of Encapsulation

Typically, there are three types of encapsulations:

1. Member variable encapsulation

The setters and getters functions in Java are used to modify or retrieve the value of a data member. This process is essentially known as member variable encapsulation.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN) 

2. Function encapsulation

Any function used for the internal implementation of an API must be declared private at all times. Any method can easily be made public since the user provides the data. Programmers should always keep a check that all functions that mustn’t be public are hidden. 

3. Class encapsulation

Almost the same principles of function encapsulation apply to class encapsulations. The classes in the program should never be a part of any public interface.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Hiding Data in Java

Encapsulation and the function of data hiding are often used interchangeably by programmers. As already mentioned above, Java encapsulation majorly deals with binding data into a single unit to maintain security and ensure more effective management. Generally, data hiding acts by restricting users to avail data member access with the help of hiding all implementation details. 

Java mainly provides the following four access modifiers:

  • Private – Public access modifiers are accessible by everyone.
  • Protected – Protected access modifiers are accessible to the subclass and contain a package.
  • Private – Private access modifiers are accessible only within their class. 
  • Default – Default access modifiers are accessible within the package. 

Tightly Encapsulated Class in Java

When each variable is declared private in a particular class, it is commonly termed a “tightly encapsulated class” in Java. In such a case, programmers must check whether the concerned class contains the getter or setter methods and whether any of those methods are declared to be public or not. 

It is important to note that when the parent class is not tightly encapsulated, the child class is automatically not tightly encapsulated. This is because the parent class’s non-private data members are by default available to every child class. Hence, we can easily conclude that data hiding, encapsulation, and tightly encapsulated class concepts are highly effective in maintaining the optimum level of security.

Why is Encapsulation Essential in Java?

Following are the several reasons which make encapsulation in Java so important:

  • Encapsulation allows its programmers to modify a code or a part of it without changing any other function in the program. 
  • Accessing data by programmers is controlled by encapsulation. 
  • Codes can be modified according to specific needs with the help of encapsulation. 
  • Encapsulations help in simplifying the applications. 


upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Advantages of Using Encapsulation in Java

Here are the top advantages of Encapsulation in Java:

  • Encapsulation averts access of private fields to other classes. 
  • It allows the modification of codes without affecting any other code in the program. This is a huge help to programmers. Without this function, the entire code could have gotten way more complicated.
  • Any encapsulated code is a lot easier to modify to meet changing requirements. 
  • Any application can be maintained in a much more efficient way with the help of encapsulation. 
  • It enhances the sense of security with users since it ensures keeping the data and codes in confidence from external inheritance.  
  • It is never visible to the user how a particular class is storing values in several variables. All the user’s information is that a setter method has been applied, and the variables are getting initialized with that value.
  • The variables can be made into read-only or write-only according to the requirements of the user or programmer.
  • Encapsulated code is always easier to use or test when it comes to unit testing.

Basic Differences Between Abstraction and Encapsulation in Java

  • Abstraction is the process of reducing an object to its essence so that only the required characteristics are visible to the user. In contrast, encapsulation is the method that helps contain the information that has been collected.
  • Problems are solved during the stages of designing and creating interfaces when it comes to attraction. On the other hand, problems are solved at the implementation stage during the process of encapsulation.
  • Abstraction is a method used to hide unwanted information, whereas encapsulation binds all the data into bundles. Those bundles are further compactly placed in one single entity or unit. It also has features to hide that information from foreign entities.
  • Abstraction can be implemented using abstract class interfaces, but encapsulations need to be implemented using any access modifier. That may be a public, private, protected, or default access modifier.
  • The objects that perform abstraction must be encapsulated. However, the objects that ultimately result in encapsulation do not necessarily require to be abstracted.
  • Implementation complexities are hidden with the help of abstract classes and interfaces, whereas the data is hidden in the encapsulation process with the help of getters and setters functions.

Upskill with upGrad

Check out upGrad’s 5-month online Job-linked PG Certification in Software Engineering to begin your career in software development. The course comprises five hands-on projects and a specialization in MERN/Cloud-Native to help build a competitive portfolio and land lucrative job opportunities.

If you are a final year student or graduate with up to 2 years of experience, the Job-linked PG Certification in Software Engineering course can be your entry-point into the software domain. 

Get in touch with us today to book your seat!

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

Frequently Asked Questions (FAQs)

1. What is the process of encapsulation?

2. What is the most major disadvantage of using encapsulation in Java?

3. What is the last step in data encapsulation?

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program