java encapsulation

Encapsulation in Java with Example

In this tutorial, you will learn about encapsulation and data hiding in Java with Example.

what is encapsulation?

In Java, encapsulation is a mechanism for combining variables (data) and methods (code) into a single unit. It is the process of concealing information details and safeguarding the object’s data and behavior. It’s one of the four key concepts in OOP. Because the encapsulating class is simple to test, it’s ideal for unit testing.

  • One of the most important aspects of object-oriented programming is encapsulation. The encapsulation of fields and methods within a single class is referred to as encapsulation.
  • It prevents outer classes from changing or accessing a class’s fields and methods. This also aids in data concealment.
In Java, encapsulation is the process of combining code and data into a single unit, such as a capsule containing several medicines.

Advantage of Encapsulation in Java

  • You can make a class read-only or write-only by providing only a setter or getter method. In other words, the getter and setter methods are optional.
  • It gives you complete control over your data. You can write the logic inside the setter method if you want to set the value of id to be greater than 100 only. You can write logic in the setter methods to prevent negative numbers from being stored.
  • Because other classes will not be able to access the data through the private data members, it is a way to achieve data hiding in Java.
  • It’s simple to test the encapsulate class. As a result, it is more suitable for unit testing.
  • The ability to generate getters and setters is provided by most standard IDEs.
Note: While many people think of encapsulation as data hiding, this isn’t entirely accurate.
The term “encapsulation” refers to the grouping of related fields and methods. This can be used to conceal information. Data hiding is not the same as encapsulation.

Java Encapsulation Example

class Area {

  // fields to calculate area
  int length;
  int breadth;

  // constructor to initialize values
  Area(int length, int breadth) {
    this.length = length;
    this.breadth = breadth;
  }

  // method to calculate area
  public void getArea() {
    int area = length * breadth;
    System.out.println("The area is: " + area);
  }
}

class Main {
  public static void main(String[] args) {

    // create object of Area
    // pass value of length and breadth
    Area rectangle = new Area(7, 6);
    rectangle.getArea();
  }
}

Output:

The area is: 42
  • We created a class called Area in the preceding example. The main goal of this class is to figure out how to calculate area.
  • We’ll need two variables: length and breadth, as well as a method: getArea to calculate an area (). As a result, we encapsulated these fields and methods in a single class.
  • The fields and methods in this class can also be accessed from other classes. As a result, this is not data concealment.
  • This is just a summary. We’re just grouping together similar codes.

Example 2: Java Encapsulation

In Java, here’s how to implement encapsulation:

  1. Make instance variables private, so they can’t be accessed from outside the class. These variables can only be set and retrieved using the class’s methods.
  2. In the class, have getter and setter methods to set and get the values of the fields.
class EncapsulationDemo{
    private int ssn;
    private String empName;
    private int empAge;

    //Getter and Setter methods
    public int getEmpSSN(){
        return ssn;
    }

    public String getEmpName(){
        return empName;
    }

    public int getEmpAge(){
        return empAge;
    }

    public void setEmpAge(int newValue){
        empAge = newValue;
    }

    public void setEmpName(String newValue){
        empName = newValue;
    }

    public void setEmpSSN(int newValue){
        ssn = newValue;
    }
}
public class EncapsTest{
    public static void main(String args[]){
         EncapsulationDemo obj = new EncapsulationDemo();
         obj.setEmpName("Louis");
         obj.setEmpAge(22);
         obj.setEmpSSN(0001);
         System.out.println("Name: " + obj.getEmpName());
         System.out.println("SSN Number: " + obj.getEmpSSN());
         System.out.println("Age: " + obj.getEmpAge());
    } 
}

Output:

Name: Louis
SSN Number: 0001
Age: 22

All three data members (or data fields) in the preceding example are private (see: Java Access Modifiers) and cannot be accessed directly. Only public methods have access to these fields. Using the OOPs encapsulation technique, the fields empName, ssn, and empAge are hidden data fields.

Data Hiding

The process is known as data hiding in Java and is accomplished by using the keyword ‘private’. It is used as a security measure to ensure that no internal data is accessed without prior authorization. Internal data will not be accessible to an unauthorized end user. Internal data will not be accessible to an unauthorized end user.

  • Data hiding is a method of limiting our data members’ access to our data by concealing the implementation details. Encapsulation also allows data to be hidden.
  • Data hiding is a software development technique used to hide internal object details in object-oriented programming (OOP) (data members). Data hiding ensures that only class members have access to data and protects object integrity by preventing unintended or intentional changes.
  •  Data encapsulation or information hiding are other terms for data hiding.

Data hiding Example:

#include<iostream>  
using namespace std;  
class Base{  
       
    int num;  //by default private  
    public:  
       
    void getData();  
    void showData();  
       
};  
void Base :: getData()  
{  
    cout<< "Enter any value" <<endl;   
    cin>>num;  
       
}  
void Base :: showData()  
{  
    cout<< "Value is " << num <<endl;  
}  
    
int main(){  
    Base obj;       
    obj.getData();  
    obj.showData();   
    return 0;  
}  

Output:

Enter any value
5
Value is 5

You may like:

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Hope this article will guide you to recognize all about Encapsulation in Java with the Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has One Comment

Leave a Reply