Java > Object-Oriented Programming (OOP) > Encapsulation > Access Modifiers (public, private, protected, default)
Encapsulation with Access Modifiers in Java
This example demonstrates encapsulation using access modifiers in Java. Encapsulation is the bundling of data (attributes) and methods that operate on that data within a class, and restricting direct access to some of the object's components. Access modifiers control the visibility of class members (variables and methods).
Code Example
This code defines a BankAccount
class. The accountNumber
and balance
fields are declared as private
, meaning they can only be accessed from within the BankAccount
class. The getAccountNumber()
and getBalance()
methods provide controlled access to these private fields. The deposit()
and withdraw()
methods encapsulate the logic for modifying the balance. The accountType
field is declared as protected
meaning it's accessible within the same package and by subclasses, even if they are in different packages. The isAccountActive()
method has default (package-private) access, meaning it is accessible only from within the same package.
public class BankAccount {
private String accountNumber;
private double balance;
protected String accountType;
public BankAccount(String accountNumber, double initialBalance, String accountType) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
this.accountType = accountType; // Setting the account type
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited " + amount + ". New balance: " + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println("Withdrew " + amount + ". New balance: " + balance);
} else {
System.out.println("Insufficient balance or invalid withdrawal amount.");
}
}
// Example of default access modifier (package-private) - no explicit modifier
boolean isAccountActive() {
return balance > 0;
}
}
Concepts Behind the Snippet
Encapsulation: Bundling data and methods that operate on the data and hiding the internal state of an object.
Access Modifiers: Keywords that control the visibility (accessibility) of class members.
Access Modifiers Explained
Real-Life Use Case
Consider a car. The engine's internal workings are hidden from the driver. The driver interacts with the car through the steering wheel, accelerator, and brakes (public methods), without needing to know the intricate details of how the engine works. Similarly, encapsulation in programming allows us to hide the complexity of a class and provide a simplified interface for interacting with it.
Best Practices
private
access for fields to protect the internal state of objects.public
getter and setter methods (if necessary) to control access to private fields.protected
access carefully, as it can break encapsulation if subclasses misuse it.
Interview Tip
Be prepared to explain the benefits of encapsulation, such as data hiding, code maintainability, and flexibility. Also, understand the differences between the access modifiers and when to use each one.
When to Use Access Modifiers
private
: When you want to strictly control access to data and prevent external modification.public
: When you want to provide unrestricted access to methods or fields. Use with caution, as it can weaken encapsulation.protected
: When you want to allow subclasses to access methods or fields, but restrict access from other classes outside the package.default
: When you want to restrict access to classes within the same package.
Alternatives
While access modifiers are the primary way to achieve encapsulation in Java, other techniques like immutability (making objects unchangeable after creation) can also contribute to data protection.
Pros of Encapsulation
Cons of Encapsulation
FAQ
-
Why is encapsulation important in OOP?
Encapsulation helps to protect the data of an object from unintended modifications and promotes code reusability and maintainability. It reduces complexity by hiding the internal workings of an object and providing a well-defined interface for interaction. -
What is the difference between
protected
anddefault
access modifiers?
protected
members are accessible within the same package and by subclasses, even if they are in different packages.default
(package-private) members are only accessible within the same package. -
When should I use `private` access modifier?
You should use the `private` access modifier when you want to restrict the access of a variable or method to only the class in which it is declared. This helps in data hiding and ensures that the internal state of the object is protected from external modification.