Programs

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.

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());

    } 

}

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.

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.

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. 

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.

What 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.

What 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.

What 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.

Want to share this article?

Be a Master in Software Development

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks