Member-only story
OOP Concepts in Java
Master Object-Oriented Programming (OOP) in Java with real-world analogies and practical code. Learn about encapsulation, inheritance, abstraction, and polymorphism in a beginner-friendly way.
Whether you’re building a small utility or a large-scale web app, understanding Object-Oriented Programming (OOP) is essential for writing clean, modular, and reusable Java code.
Java is 100% object-oriented (except for primitives), and mastering OOP concepts will help you:
- Think in terms of real-world objects.
- Reduce duplication (DRY principle).
- Create a scalable software architecture.
In this guide, you’ll learn the four core OOP principles with real-world examples and Java code snippets.
📦 1. Encapsulation — Wrapping Data for Protection
Encapsulation is the binding of data (fields) and the code (methods) that manipulates it into a single unit (class), while restricting direct access to that data.
🔐 Why is Encapsulation Important?
💡 Real-World Analogy:
Think of a medicine capsule — it wraps the drug inside so it’s not directly exposed. Similarly, encapsulation wraps data and restricts direct access.
👨💻 Java Example:
public class BankAccount {
private double balance;
public void deposit(double amount) {
if(amount > 0) balance += amount;
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) balance -= amount;
}
public double getBalance() {
return balance;
}
}
✅ Key Takeaways:
balance
is private (hidden).- Access is allowed only via public methods (
getBalance
,deposit
,withdraw
). - This protects the internal state of the object.