⬅ Previous Topic
Polymorphism in JavaNext Topic ⮕
Java Nested Classes⬅ Previous Topic
Polymorphism in JavaNext Topic ⮕
Java Nested ClassesEncapsulation in Java is a core concept of Object-Oriented Programming (OOP) that allows you to bundle data (variables) and methods (functions) that operate on the data into a single unit: the class. More importantly, it enables data hiding — restricting direct access to class fields from outside code, while still providing controlled access through methods.
Without encapsulation, our classes would be exposed — any part of the codebase could directly modify the internal state of objects. That’s a recipe for unpredictable behavior. Encapsulation ensures:
Let’s break it down into steps:
private
Private fields cannot be accessed directly from outside the class.
public
getter and setter methodsThese methods allow controlled read/write access to the fields.
public class BankAccount {
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Getter for accountHolder
public String getAccountHolder() {
return accountHolder;
}
// Setter for accountHolder
public void setAccountHolder(String name) {
accountHolder = name;
}
// Getter for balance
public double getBalance() {
return balance;
}
// Setter for balance
public void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
System.out.println("Balance cannot be negative.");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 5000);
// Accessing data via getters
System.out.println("Account Holder: " + account.getAccountHolder());
System.out.println("Initial Balance: $" + account.getBalance());
// Modifying data via setters
account.setBalance(7000);
System.out.println("Updated Balance: $" + account.getBalance());
// Trying to set invalid balance
account.setBalance(-100);
}
}
Account Holder: Alice
Initial Balance: $5000.0
Updated Balance: $7000.0
Balance cannot be negative.
If fields were public, any class could change the values without any checks. For instance:
account.balance = -10000; // This would be allowed if 'balance' was public
This is dangerous. You lose control over your class’s integrity. With encapsulation, such reckless modifications can be blocked.
Think of encapsulation like using a vending machine. You interact with it through buttons (public methods) — you don’t get to reach inside and grab a drink (private fields). It controls what happens internally based on your input.
private
for fieldspublic
getters and setters to expose controlled accessaccount.balance = -10000;
⬅ Previous Topic
Polymorphism in JavaNext Topic ⮕
Java Nested ClassesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.