Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Encapsulation in Java

Last Updated on January 30, 2023 by Sumit Kumar

Data Encapsulation in Java, a distinguishing feature of Object-Oriented Programming, ties or groups together similar code units, improving the organization of the code. Encapsulation in Java aids in data hiding, by prohibiting unwanted access to the implementation details. It is also known as data hiding because it shields the user from learning about a class’s implementation.

In this article, we will learn Encapsulation in Java with examples. We will discuss various Use cases of Data Encapsulation in Java. The concept of Data Hiding along with its role is explained in the article. We will also look at various advantages provided by Encapsulation in java. At the end of the article, you will be able to understand the concept of encapsulation in java with examples.

Data Encapsulation in Java with Examples

Data encapsulation is a fundamental concept in object-oriented programming, and it is heavily used in Java. It refers to the practice of hiding the internal state and behavior of an object from the outside world and only exposing a limited set of methods and properties that allow external objects to interact with it. This helps in maintaining the integrity and consistency of the data, and it also makes the code more maintainable and less prone to errors.


Visual Representation of Encapsulation in Java

Some Important Points about Encapsulation in Java

Encapsulation is considered to be one of the four pillars of Object Oriented Programming. Some of the important points that we must understand about encapsulation in java are given in brief below:

  • Technically speaking, encapsulation means that a class’s variables or data are hidden from all other classes and are only accessible through member functions of the class in which they are stated.
  • Data encapsulation also promotes the use of object-oriented programming principles such as abstraction and inheritance. Abstraction refers to the practice of hiding the implementation details of an object and only exposing the necessary information to the outside world. Inheritance refers to the ability of a subclass to inherit the properties and methods of a superclass. Data encapsulation allows the developer to use these principles to create a more organized and modular codebase.
  • With the setter and getter methods, Encapsulation in java is more clearly described.
  • Declaring all class variables as private and creating public methods for setting and obtaining variable values are two ways to accomplish encapsulation in java.

Examples of Encapsulation in Java:

Let us understand the Encapsulation in java with examples. Consider the code given below:

class PrepBytes {
    private String str;
    
    public String getString() {
    	return str;
    }
    
    public void setString(String str) {
    	this.str = str;
    }
}

public class Main {
    public static void main(String[] args) {
    	PrepBytes obj = new PrepBytes();
    	obj.setString("My String");
    	System.out.println(obj.getString());
    }
}

Output:

My String

In the above example code, we have declared the setter function “setString()” and the getter function “getString()” and we have accessed the private data member using the setter and getter methods.

Now if we try to directly access the private data member i.e. string, we will get a compiler error as shown in the below code and output:

class PrepBytes {
    private String str;
    
    public String getString() {
    	return str;
    }
    
    public void setString(String str) {
    	this.str = str;
    }
}

public class Main {
    public static void main(String[] args) {
    	PrepBytes obj = new PrepBytes();
    	obj.setString("My String");
    	System.out.println(obj.getString());
    	
    	//This line will give compile error
    	//because we are trying to access private data member
    	System.out.println(obj.str);
    }
}

Output:

Main.java:21: error: str has private access in PrepBytes
        System.out.println(obj.str);
                              ^

How we can Implement Data Encapsulation in Java

Encapsulation in Java may be achieved in a few different ways. Among them are:

  • We should declare the class variables as private to make them inaccessible from the outside scope of the class.
  • We should define the getter and setter methods according to the requirements. The setter and getter methods define the type of class that whether the class is “Read-only” or “Write-only”.

Read-Only Classes using Encapsulation in Java

A read-only class is one where you can access the variable values but not modify them. By removing a class’ setter methods, one can convert it into a read-only class. We’ll examine an example to help clarify the next idea. To make the class "read-only," we will remove the setter methods from the aforementioned program.

Code:

//Read Only Class
class PrepBytes {
    private String str;
    
    PrepBytes(){
        str = "My string";
    }
    
    public String getString() {
    	return str;
    }
    
    // public void setString(String str) {
    //   	this.str = str;
    // }
}

public class Main {
    public static void main(String[] args) {
    	PrepBytes obj = new PrepBytes();
    	System.out.println(obj.getString());
    }
}

Output:

My string

Explanation: We have made the class “PrepBytes” Read-Only by removing the Setter method. Now we can only read the data present in this class but cannot re-assign anything to the data.

Write-Only Classes using Encapsulation in Java

Write-only classes, or classes that let you write onto variables but not read them, can exist. In essence, this means that you are allowed to change a variable but not examine it or see its value.
By eliminating the getter methods from the class specification, we may make a class write-only.

Code:

//Read Only Class
class PrepBytes {
    private String str;
    
    PrepBytes(){
        str = "My string";
    }
    
    // public String getString() {
    //   	return str;
    // }
    
    public void setString(String str) {
      	this.str = str;
    }
}

public class Main {
    public static void main(String[] args) {
    	PrepBytes obj = new PrepBytes();
    	obj.setString("New String");
    }
}

Explanation: In the above code, we do not get any output on the standard output, since we have made the class “PrepBytes” Write-Only by removing the Getter method. Now we can only update the data, but cannot read the data because of the absence of the getter function and the method is private.

Data Hiding in Java

Data hiding in Java refers to the practice of keeping the internal state of an object hidden from the outside world and only exposing a public interface for interacting with the object. This can be achieved by using the "private" access modifier for class variables and methods and using "getter" and "setter" methods to access and modify the internal state. This allows for the encapsulation of the data and helps to maintain the integrity of the object’s state.

Key Difference between Encapsulation and Data Hiding in Java

Data hiding and encapsulation are often used interchangeably, but they are slightly different concepts in Java.

Encapsulation refers to the practice of binding the data (variables) and the methods that operate on that data within a single unit (such as a class). It is a mechanism of wrapping the data and the methods that manipulate the data within a single unit so that the data can be protected from outside interference and misuse. Encapsulation is achieved in Java through the use of classes and objects.

Data hiding, on the other hand, refers to the practice of hiding the internal state of an object from the outside world. It is a specific aspect of encapsulation and it is achieved in Java by using the "private" access modifier for variables and methods. By making the variables and methods private, they can only be accessed or modified through the public methods that are provided by the class, known as getter and setter methods.

In summary, encapsulation is the overall concept of binding data and methods together within a unit, while data hiding is a specific aspect of encapsulation that deals with hiding the internal state of an object from the outside world.

Advantages of Encapsulation in Java

  • Encapsulation makes Programming Flexible – Depending on our needs, we may make the class’s variables read-only or write-only. If we want to make the variables read-only, we must remove the setter methods from the program or if we want to make the variables write-only, we must remove the get methods. This is the biggest advantage of encapsulation in Java.
  • Simpler testing and debugging – The encapsulated code is simple to test and debug.
  • Reusability – You may use the code again and add new specifications to your software.
    Encapsulated code is much easier to reuse as the programmer does not need to worry about other methods.
  • Data Hiding – Encapsulated code helps in hiding all of the implementation details of the function from the external functions. For instance, the user will never be able to learn what variables the application is using to store data. They will communicate with the program’s getter and setter methods.
  • Reduce Coupling: Encapsulated Code helps in reducing the coupling between various methods in the programs.

Conclusion
In conclusion, data encapsulation is a fundamental concept in object-oriented programming, and it is heavily used in Java. It refers to the practice of hiding the internal state and behavior of an object from the outside world and only exposing a limited set of methods and properties that allow external objects to interact with it. This helps in maintaining the integrity and consistency of the data, and it also makes the code more maintainable and less prone to errors.

Leave a Reply

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