Open In App

Encapsulation in Java

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, encapsulation is one of the coret concept of Object Oriented Programming (OOP) in which we bind the data members and methods into a single unit. Encapsulation is used to hide the implementation part and show the functionality for better readability and usability. The following are important points about encapsulation.

  • Better Code Management : We can change data representation and implementation any time without changing the other codes using it if we keep method parameters and return values same. With encapsulation, we ensure that no other code would have access to implementation details and data members.
  • Simpler Parameter Passing : When we pass an object to a method, everything (associated data members and methods are passed along). We do not have to pass individual members.
  • getter and setter: getter (display the data) and setter method ( modify the data) are used to provide the functionality to access and modify the data, and the implementation of this method is hidden from the user. The user can use this method, but cannot access the data directly.

Example: Below is a simple example of Encapsulation in Java.

Java
// Java program demonstrating Encapsulation
class Programmer {
    
    private String name;

    // Getter and Setter for name
    
    // Getter method used to get the data
    public String getName() { return name; }
    
    // Setter method is used to set or modify the data
    public void setName(String name) { this.name = name; }
}

public class Geeks {
    
    public static void main(String[] args) {
        Programmer p = new Programmer();
        p.setName("Geek"); 
        System.out.println("Name=> " + p.getName());
    }
}

Output
Name=> Geek

Explanation: In the above example, we use the encapsulation and use getter (getName) and setter (setName) method which are used to show and modify the private data. This encapsulation mechanism protects the internal state of the Programmer object and allows for better control and flexibility in how the name attribute is accessed and modified.

Uses of Encapsulation in Java

Using encapsulation in Java has many benefits:

  • Data Hiding: The internal data of an object is hidden from the outside world, preventing direct access.
  • Data Integrity: Only validated or safe values can be assigned to an object’s attributes via setter methods.
  • Reusability: Encapsulated code is more flexible and reusable for future modifications or requirements.
  • Security: Sensitive data is protected as it cannot be accessed directly.

This image below demonstrates the concept of encapsulation, where a class (represented by the capsule) hides its internal data (variables) and only exposes a controlled interface (encapsulation).


Implementation of Java Encapsulation

In Java, encapsulation is implemented by declaring instance variables as private, restricting direct access. Public getter methods retrieve variable values, while setter methods modify them, enabling controlled access. This approach allows the class to enforce data validation and maintain a consistent internal state, enhancing security and flexibility.

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, that it is a protective shield that prevents the data from being accessed by the code outside this shield. 

  • In encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of its own class.
  • A private class can hide its members or methods from the end user, using abstraction to hide implementation details, by combining data hiding and abstraction.
  • Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
  • It is more defined with the setter and getter method.

Example 1: Here is another example of encapsulation in Java.

Java
// Java program to demonstrate the Encapsulation.
class Person {
    
    // Encapsulating the name and age
    // only approachable and used using
    // methods defined
    private String name;
    private int age;

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }

    public void setAge(int age) { this.age = age; }
}

// Driver Class
public class Geeks {
    
    // main function
    public static void main(String[] args)
    {
        // person object created
        Person p = new Person();
        p.setName("Sweta");
        p.setAge(25);
        
        // Using methods to get the values from the
        // variables
        System.out.println("Name: " + p.getName());
        System.out.println("Age: " + p.getAge());
    }
}

Output
Name: Sweta
Age: 25

Explanation: Here, the encapsulation is achieved by restricting direct access to the name and age fields of the Person class. These fields are marked as private and can only be accessed or modified through public getter and setter methods (getName(), setName(), getAge(), setAge()). This approach ensures data hiding and maintains control over the values of these fields.


Example 2: In this example, we use abstraction to hide the implementation and show the functionality.

Java
class Area {
    private int l; // this value stores length
    private int b; // this value stores breadth

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

    // method to calculate area
    public void getArea()
    {
        int area = l * b;
        System.out.println("Area: " + area);
    }
}

public class Geeks {
    public static void main(String[] args)
    {
        Area rect = new Area(2, 16);
        rect.getArea();
    }
}

Output
Area: 32

Explanation: In the above example, Area class and inside the class we create a constructor which takes two parameters l (length) and b (breath) and a getArea() method to calculate the area of ranctangle. This method shows the abstraction where the implementation (Calculating area) is hidden and functionality is showing (Area of rectangle).


Example 3: The program to access variables of the class Geeks is shown below:  

Java
// Java program to demonstrate 
// Java encapsulation

class Encapsulate {
    // private variables declared
    // these can only be accessed by
    // public methods of class
    private String geekName;
    private int geekRoll;
    private int geekAge;

    // get method for age to access
    // private variable geekAge
    public int getAge() { return geekAge; }

    // get method for name to access
    // private variable geekName
    public String getName() { return geekName; }

    // get method for roll to access
    // private variable geekRoll
    public int getRoll() { return geekRoll; }

    // set method for age to access
    // private variable geekage
    public void setAge(int newAge) { geekAge = newAge; }

    // set method for name to access
    // private variable geekName
    public void setName(String newName)
    {
        geekName = newName;
    }

    // set method for roll to access
    // private variable geekRoll
    public void setRoll(int newRoll) { geekRoll = newRoll; }
}

// Main Class
public class Geeks
{
    public static void main(String[] args)
    {
        Encapsulate o = new Encapsulate();

        // setting values of the variables
        o.setName("Geeky");
        o.setAge(19);
        o.setRoll(51);

        // Displaying values of the variables
        System.out.println("Geek's name: " + o.getName());
        System.out.println("Geek's age: " + o.getAge());
        System.out.println("Geek's roll: " + o.getRoll());

        // Direct access of geekRoll is not possible
        // due to encapsulation
        // System.out.println("Geek's roll: " +
        // obj.geekName);
    }
}

Output
Geek's name: Geeky
Geek's age: 19
Geek's roll: 51

Explanation: Here, the class Encapsulate keep its variable private, it simply means that they can not be accessed direclty from outside the class. To get the values of these variables we need to use public methods. This way the data can only be accessed or changed through these methods.


Example 4: Let us go through another example, to understand the concept better.

Java
// Java Program which demonstrate Encapsulation
class Account {
    
    // Private data members (encapsulated)
    private long accNo; // Account number 
    private String name;
    private String email;
    private float amount;

    // Public getter and setter methods (controlled access)
    public long getAccNo() { return accNo; }
    public void setAccNo(long accNo) { this.accNo = accNo; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public float getAmount() { return amount; }
    public void setAmount(float amount) { this.amount = amount; }
}

// Main Class
public class Geeks 
{
    public static void main(String[] args) 
    {
        // Create an Account object
        Account acc = new Account(); 

        // Set values using setter methods (controlled access)
        acc.setAccNo(90482098491L);
        acc.setName("ABC");
        acc.setEmail("[email protected]");
        acc.setAmount(100000f);

        // Get values using getter methods
        System.out.println("Account Number: " + acc.getAccNo());
        System.out.println("Name: " + acc.getName());
        System.out.println("Email: " + acc.getEmail());
        System.out.println("Amount: " + acc.getAmount());
    }
}

Output
Account Number: 90482098491
Name: ABC
Email: [email protected]
Amount: 100000.0

Explanation: Here, we are using encapuslation and hiding all the details inside the Account class. We can not access all the details from outside the class, to access all the details we need to create getter and setter methods so that we can easily get and update the details. In the main method, an Account object is created so that values can be set using the setter and get the value using getter.


Advantages of Encapsulation

The advantages of encapsulation are listed below:

  • Data Hiding: Encapsulation is used to hides the details of a class. We do not need to worry about how it works. It just use the setter methods to give values to the variables.
  • Data Integrity: With the help of setter and getter methods we can ensure that the correct data is assigned to the variable.
  • Reusability: Witht the help of encapuslation the readability of the code increases also the changing of code becomes eaiser when we need to add new feature in the code.
  • Testing code is easy: Encapsulated code is easy to test for unit testing.
  • Freedom of advantages the details: one of the major advantages of encapsulation is that it gives the programmer freedom to implement the details of a system. The only constraint on the programmer is to maintain the abstract interface that outsiders see. 

Disadvantages of Encapsulation

The disadvantages of encapsulation are listed below:

  • Sometimes encapuslation can make the code complex and hard to understand if we do not use it in the right way.
  • It can make it more difficult to understand how the program works because some part of the program are hidden.

Common Mistakes To Avoid

The common mistakes that can occur when working with encapsulation in Java are listed below:

  • Exposing Internal Data Directly: Changing or reading the class variables directly without using getter and setter, breaks the encapuslation concepts.
  • Not Using Access Modifiers Correctly: Not using correct access modifier can allow unauthorzied access to the data.
  • Overuse of Public Methods: Making all the methods public is not a good practice, only declared needed methods to be public so that the data keep safe.
  • Failing to Validate Input: If we don’t check the values before setting them, wrong or bad data can go into the class, which may cause problems later.

Best Practices

  • Use Private Fields: Keep the class varaibles as private so that no one outside the class can change them directly.
  • Use Getter and Setter Methods: Use getters to get the value and setters to change the value.
  • Control Access with Access Modifiers: Use access modifiers the right way to hide what should be hidden and show only what is needed.
  • Validate Data Before Modifying: Always check the data inside setter methods before saving it to make sure it is correct.

Next Article
Article Tags :
Practice Tags :

Similar Reads