PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Encapsulation in Java

← All stacks

Theory

49/270

Encapsulation in Java

Encapsulation means keep data private and change it only through safe methods. Imagine a locker. You don’t let everyone open the door and throw money in or out. You give deposit() and getBalance(). Inside deposit you can reject a negative amount. That is the whole pillar.

Let’s take this on the board. class BankAccount { private double balance; void deposit(double amt) { if (amt > 0) balance += amt; } double getBalance() { return balance; } }. Then BankAccount acc = new BankAccount(); acc.deposit(100); acc.deposit(-50); print acc.getBalance();. Output: 100. The -50 was ignored. Outside code cannot write acc.balance = -99 because balance is private. Compile error. That error is your friend.

If balance is public, any line in the project can smash the rules. That is the beginner mistake: “public for speed”. Interviews almost always ask this pillar. Show private field + validating method. Getters are OK; a clear action like deposit/withdraw is even better than a blank setBalance that accepts anything.

Encapsulation is not only private. It is private + a door that checks. A private field with a setter that accepts every value is a locked locker with the key taped on the door.

Diagram
BankAccount
    private balance
         │ only via
         ▼
    deposit() / getBalance()
Exam tip

private balance + validating deposit() is the encapsulation demo.

Example

class Account {
  private int balance = 0;
  public int getBalance() { return balance; }
  public void deposit(int amount) {
    if (amount > 0) balance += amount;
  }
}
public class Main {
  public static void main(String[] args) {
    Account a = new Account();
    a.deposit(100);
    System.out.println(a.getBalance());
  }
}

Encapsulation in Java — output: 100. Main cannot write a.balance — it is private. deposit(100) updates it; getBalance reads it.

Short notes

  • DefEncapsulation = hide data. Change it only through safe methods.
  • Ruleprivate fields + deposit/getBalance (or getters/setters).
  • RememberValidate inside the method. Reject negative deposit.
  • TrapPublic fields let anyone put invalid values.

Questions

1

What is encapsulation?

2

Why private fields?

3

Show a tiny example.

Previous← Access Modifiers in JavaNextJava Arrays →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.