Java Encapsulation

java

Encapsulation is a fundamental principle of object-oriented programming (OOP) that refers to the bundling of data with the methods that operate on that data, or the hiding of data implementation details from the outside world. In Java, encapsulation is implemented using access modifiers, which determine the visibility and accessibility of class members ( fields and methods). There are four access modifiers in Java: public, protected, default (or package-private), and private.

Encapsulation is useful because it helps to hide the implementation details of a class from the outside world, making it easier to change the implementation without affecting other parts of the program. It also helps to promote modularity and reusability of code.

To implement encapsulation in Java, you can use access modifiers to control the visibility and accessibility of class members. For example, you can mark a field as private to prevent it from being accessed directly from outside the class. You can then provide public methods to allow other parts of the program to access or modify the field in a controlled manner.

Here is an example of encapsulation in Java:

public class BankAccount {
  private double balance;

  public double getBalance() {
    return balance;
  }

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

In this example, the balance field is marked as private, meaning it can only be accessed from within the BankAccount class. To access the balance from outside the class, we have provided public getBalance() and setBalance() methods, which allow us to retrieve and update the balance respectively. This allows us to control access to the balance field and ensure that it is only modified in a controlled manner.