QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Intermediate 16 min readModule: Module 4: Object-Oriented Programming (Classes & Objects)

Classes, Constructors & Encapsulation

Design object-oriented classes with private fields, public getters/setters, and overloaded constructors.

What You Will Learn in This Lesson

  • Encapsulation: hiding internal state behind accessors
  • Constructor overloading and the 'this' keyword
  • Static class members vs instance variables

Introduction & Core Concept

Object-Oriented Programming (OOP) organizes software design around data objects rather than functions and logic.
WHY DOES THIS MATTER IN THE REAL WORLD?

Encapsulation protects class invariants by validating mutations inside setter methods before assignment.

Encapsulated Account Class

java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BankAccount {
private final String accountNumber;
private double balance;
public BankAccount(String accNum, double initial) {
this.accountNumber = accNum;
this.balance = Math.max(0, initial);
}
public void deposit(double amount) {
if (amount > 0) this.balance += amount;
}
public double getBalance() { return this.balance; }
}

Line-by-Line Technical Breakdown

1static fields belong to the class itself, shared across all instantiated objects.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[JAVA]
JAVA SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Always make fields private final whenever possible.

Lesson Summary & Core Takeaways

  • Encapsulation and constructors form the foundation of robust Java design.