Encapsulation in Java

Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) and refers to the process of hiding the internal details of an object from the outside world. In Java, encapsulation is achieved by declaring the instance variables of a class as private and providing public getter and setter methods to access and modify these variables.

Here's an example of encapsulation in Java:

                
    public class BankAccount {
      private double balance;

      public double getBalance() {
        return balance;
      }

      public void setBalance(double balance) {
        if (balance >= 0) {
          this.balance = balance;
        }
      }
    }
                
            

In this example, we have a BankAccount class with a private instance variable balance. The getBalance() method is used to get the value of balance, and the setBalance() method is used to set the value of balance. Since balance is declared as private, it can only be accessed or modified by the methods inside the class.

The setBalance() method includes a condition that ensures that the balance is never negative. This is an example of encapsulation because the implementation details of the balance variable are hidden from the outside world, and the access and modification of the variable are controlled through the public methods.

Encapsulation has several benefits, including data protection, security, maintainability, and flexibility. By hiding the internal details of an object, encapsulation ensures that the object's data is protected from unauthorized access or modification. It also makes the code easier to maintain and modify since the implementation details can be changed without affecting the public interface.