Encapsulation is a key concept in object-oriented programming that involves bundling data and methods that operate on that data within a single unit called a class. The goal of encapsulation is to hide the implementation details of the class from the outside world, and provide a well-defined public interface that can be used to interact with the class.
In Java, encapsulation is typically achieved by using access modifiers to restrict the visibility of the class’s data and methods. The private
modifier is used to make a field or method accessible only within the class where it is defined. The public
modifier is used to make a field or method accessible from any other class in the program. The protected
modifier is used to make a field or method accessible within the class and its subclasses.
Here’s an example of encapsulation in Java:
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
In this example, the BankAccount
class encapsulates a bank account balance using a private field called balance
. The class provides two public methods (deposit()
and withdraw()
) that allow you to modify the balance, and a public method (getBalance()
) that allows you to retrieve the balance. By encapsulating the balance within the class and providing a public interface to modify and retrieve it, the class hides the implementation details of how the balance is stored and manipulated, which makes it easier to maintain and modify the class without affecting other parts of the program.
Encapsulation is an important principle in OOP, and it provides a way to create more secure, maintainable, and reusable code by hiding the internal details of a class and exposing only the necessary functionality to the outside world.