🟣 OOP  ·  Lesson 22

Encapsulation

Encapsulation

What is Encapsulation?

Encapsulation means wrapping data (fields) and methods together, and hiding fields with private, exposing them through getters and setters.

Example

class Account {
    private double balance;   // hidden
    public void deposit(double amt) { balance += amt; }
    public double getBalance() { return balance; }
}

Account a = new Account();
a.deposit(500);
System.out.println(a.getBalance());
500.0

Why Encapsulate?

  • Protects data from invalid changes.
  • You control access through methods (e.g. validate before setting).

Summary

  • Encapsulation = private fields + public getters/setters.
  • Protects and controls access to data.

Encapsulation क्या है?

Encapsulation मतलब data (fields) और methods को एक साथ लपेटना, और fields को private से छुपाकर getters/setters से expose करना।

Example

class Account {
    private double balance;   // छुपा हुआ
    public void deposit(double amt) { balance += amt; }
    public double getBalance() { return balance; }
}

Account a = new Account();
a.deposit(500);
System.out.println(a.getBalance());
500.0

Encapsulate क्यों?

  • Data को गलत बदलावों से बचाता है।
  • आप methods से access control करते हैं (जैसे set करने से पहले validate)।

सारांश

  • Encapsulation = private fields + public getters/setters।
  • Data को protect और access control करता है।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n