Java Encapsulation

One of the four essential OOPS concepts is encapsulation. The remaining three are abstraction, polymorphism, and inheritance. In Java, encapsulation is a way of combining the code that manipulates the data and the data itself into a single unit. Encapsulation means that a class's variables are kept private from other classes and are only accessible through its own methods. As a result, it is sometimes referred to as data concealing. In this article, we will be talking about data hiding in Java, and the need and advantages for encapsulation in Java.

What is Java Encapsulation

Java encapsulation is a process where a class's variables or data are concealed from all other classes and are only accessible through member functions of the class in which they were declared. It is also known as a combination of data-hiding and abstraction because, similar to encapsulation, the data in a class is hidden from other classes using the data hiding concept, which is accomplished by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation.

Encapsulation is accomplished by writing public functions in the class for setting and getting the values of the variables and declaring all of the class's variables as private.

With the setter and getter methods, it is more clearly described. Encapsulation is majorly of 3 types:

  • Encapsulation of member variables: All data members in object-oriented programming should be designated as class's private members. This type of encapsulation is not the sole method of data encapsulation, though. Additionally, classes and functions can be encapsulated.
  • Function Encapsulation: You must always define all functions that are utilised solely internally by your API as Private. Your API's internal implementation functions must always be marked private.
  • Class Encapsulation: The classes in class encapsulation shouldn't be a part of  any API's public interface. Your users should not see these, therefore make them private. For instance, your API might contain a class that, depending on a circle's position, applies a specific gradient colour to it. You should encapsulate, or define it as a Private class, if your user does not require access to this Gradient class.

Let us see a simple Java code and understand the concept of encapsulation better:

class Area_Rectangle {
int len;
int br;

Area_Rectangle(int len, int br) {
this.len = len;
this.br = br;
}

public void getArea() {
int area = len * br;
System.out.println("Area of the rectangle is: " + area);
}
}

class Main {
public static void main(String[] args) {
Area_Rectangle rectangle = new Area_Rectangle(4, 16);
rectangle.getArea();
}
}

Output:

Area of the rectangle is: 64


Now, let us see another Java code for encapsulation where the program demonstrated how to access the variables of the class.

class Encapsulation {
private int age;
public int getAge() { return age; }
public void setAge(int age)
{
this.age = age;
}
}
class ABC {
public static void main(String[] args)
{
Encapsulation n1 = new Encapsulation();
n1.setAge(25);
System.out.println("The age is: " + n1.getAge());
}
}

Output:

The age is: 25

Wish to make a career in the world of Java? Start with HKR'S Java Training !

Need for Java Encapsulation

Let us discuss the need for encapsulation in Java:

  • Encapsulation enables us to group together relevant fields and procedures, which results in cleaner, easier-to-read code.
  • It makes it easier to manage the values in our data fields.
  • Our class fields can be accessed read-only or write-only using the getter and setter methods.
  • Decoupling system components is beneficial. For instance, we can divide code up into different bundles. It is possible to build, test, and debug this bundle of disconnected components simultaneously and independently. Additionally, any modifications to one component have no impact on the functioning of any other components.
  • The data members and data methods inside the class are completely under your control thanks to encapsulation.
  • Encapsulation can also be used to hide data. If we make the variables private, then access to the fields becomes restricted.

If you have any doubts on Java, then get them clarified from Java Industry experts on our Java Community !

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Advantages of Java Encapsulation

  • Data Hiding: Encapsulation is achieved by defining all class variables as private and writing public functions in the class to set and obtain variable values. It is better explained with the help of setter and getter methods.
  • Flexibility: Depending on our needs, we can 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 aforementioned program, such as seAge() and setName(), or if we want to make the variables write-only, we must remove the get methods, such as getAge() and getName().
  • Reusability of code: Additionally, encapsulation makes it easier to reuse code and adapt to changing needs.
  • Easy testing of code: For unit testing, encapsulated code is simple to test.
  • Control over Data: The user can implement the logic inside the setter method if he wishes to set an ID value that must be greater than 100 alone. He can program the setter methods with logic that prevents the storage of negative integers.

   Top 30 frequently asked JAVA Interview Questions !

Subscribe to our youtube channel to get new updates..!

Data Hiding in Java

A process called as data concealing is employed to restrict access to the data methods, data members, and the logical implementation. Utilising access specifiers will enable data concealing. The following are the four access specifiers that we have :

  • Default : The initial line of data concealing is default. The compiler will set "default" as the access specifier for any Java class that is not explicitly described within an access specifier. The default access specs and the public access specifier are remarkably similar.
  • Public : A class's access specifications are provided by the public access specifier, enabling access to it from anywhere in the application. Check out the java program below to understand public data member :
package P;
public class X
{
public void display()
{
System.out.println("Welcome to HKR Trainings");
}
}

The output of the Java code is:

Welcome o HKR Trainings
  • Protected : Similar to the private specifier, the protected access specifier safeguards the class members and methods. The primary distinction is that, as opposed to only a class having the private access specifier, access is restricted to the entire package. Check out the java program below to understand protected data member :
package P;

public class X

{

protected void display()

{

System.out.println("Welcome o HKR Trainings");

}

}
  • Private : The data members are accessible via the private access specifier, whereas only the class itself is accessible via the data methods. Check out the java program below to understand private data member :
package P;

class X

    {

    private void display()

{

System.out.println("Welcome to HKR Trainings);

}

}

class Y

    {

    public static void main(String args[])

{

X obj = new X();

obj.display();

}

}

The output will be:


.java
error: invalid flag: /tmp/iREEX2TaoL/Y
Usage: javac
use --help for a list of possible options
dash: 2: .java: not found

Want to know more about Java,visit here Java Tutorial !

Java Certification Training

Weekday / Weekend Batches

Conclusion

In this article, we have discussed Java encapsulation in depth. Java encapsulation is a process where a class's variables or data are concealed from all other classes and are only accessible through member functions of the class in which they were declared. It is also known as a combination of data-hiding and abstraction. We have also discussed the need and advantages of java encapsulation along with the data hiding in java using private, public, default and protected.

Related Article

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 6th Jun 2023, Weekday batch

  • Batch starts on 10th Jun 2023, Weekend batch

  • Batch starts on 14th Jun 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

Encapsulation is a process where a class's variables or data are concealed from all other classes and are only accessible through member functions of the class in which they were declared.

The three types of encapsulation are member variable encapsulation, class encapsulation and function encapsulation.

A structured data object's values or state are buried inside a class using encapsulation to prevent direct client access that can reveal undocumented implementation details or compromise state invariance upheld by the methods.

When a lower-layer protocol gets data from a high-layer protocol, it encapsulates the data and inserts it into the data component of its frame.

We can ourselves define the encapsulation as public or private.