Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconEncapsulation in Java with Example

Encapsulation in Java with Example

Last updated:
17th Jan, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Encapsulation in Java with Example

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:

Ads of upGrad blog
  • 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

Explore Our Software Development Free Courses

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.

Explore our Popular Software Engineering Courses

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.

In-Demand Software Development Skills

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.

Read our Popular Articles related to Software Development

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.

Ads of upGrad blog

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.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What is the process of encapsulation?

Encapsulation is a process that begins with picking up or collecting data from a particular format. Then that data is translated and reformatted into another format or protocol, according to the requirement of the programmer or user. This allows the data to be accessible across any application or network while maintaining the optimum security level for that data.

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

Even though encapsulation is one of the most effective functions in Java, which helps simplify a lot of processes for programmers, the only disadvantage faced by its users is that it increases the length of the code by a vast amount and, in turn, slows down the operation or execution of shutting down the device.

3What is the last step in data encapsulation?

The last step of the process of encapsulation in Java comprises transforming the user information into equivalent data. After this step, the same data is distributed into segments which are further segregated into several data packets. Data packets are commonly placed into logical frames that help them transfer to and fro within the software environment according to requirements.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Best Jobs in IT without coding
134275
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers & Experienced [2023]
900305
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers & Experienced [2024]
905070
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5021
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5134
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5054
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5132
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5059
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5138
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon