Encapsulation in Java is the Object-Oriented Programming (OOP) principle of bundling variables (data) and methods (behavior) together into a single unit (a class) while restricting direct access to the internal state.
How to Achieve Encapsulation
✓ Declare class variables as private to hide them from direct outside manipulation.
✓ Provide public getter and setter methods to allow controlled read and write operations.
Key Rules:
Declare data as private: Hide the class data so it cannot be accessed directly from outside the class.
Use getters and setters: Keep variables private and provide public getter and setter methods for controlled access and safe modification.
Apply proper access modifiers: Use private for data hiding and
public for methods that provide access.
Example Code
public class ATM
{
private int money = 20000;
public int getMoney(){
return this.money;
}
public void setMoney(int money){
if(money <= 20000){
this.money = money;
System.out.println("Withdrawal Sucessfull.");
}
else{
System.out.println("Withdrawal failed! Maximum withdrawal limit is ₹20,000 per transaction.");
}
}
}
public class User
{
public static void main(String[] args) {
ATM atm = new ATM();
System.out.println("Withdrawal limit per transaction: ₹" +atm.getMoney());
atm.setMoney(21000);
System.out.println("Your Withdrawal Money only 20000 or below 20000: ₹" +atm.getMoney());
}
}
Output
public class User
{
public static void main(String[] args) {
ATM atm = new ATM();
System.out.println("Withdrawal limit per transaction: ₹" +atm.getMoney());
atm.setMoney(15000);
System.out.println("Your Withdrawal Money is only 20000 or below 20000: ₹" +atm.getMoney());
}
}


Top comments (0)