Introduction
If you’re new to software engineering, you’ve probably heard the term “object-oriented programming,”* or OOP. It’s a fundamental way to write code that models real-world objects and behaviors. In this blog, I’ll explain the four main principles of OOP with simple real-life examples and Java code snippets. Whether you’re just starting or need a quick refresher, this guide will help you grasp the core concepts!
What is object-oriented programming (OOP)?
OOP organizes your code by bundling data and functions into objects. It makes your programs easier to reuse, scale, and maintain.
The four pillars of OOP are,
- Encapsulation
- Inheritance
- Polymorphism
Abstraction
Encapsulation
Encapsulation means keeping data and methods together inside a class and restricting access to the internals.
Analogy: Like a TV remote — you press buttons without seeing the internal circuits.
Example in Java:
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
- Inheritance
Inheritance lets a class inherit properties and methods from another, promoting code reuse.
Analogy: A Dog is an Animal — it inherits common traits but has unique features.
Example:
public class Animal {
public void eat() {
System.out.println("Eating...");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Barking...");
}
}
- Polymorphism
Polymorphism means “many forms” — methods behave differently based on the object.
Analogy: The word run means different actions for a person and a program.
Example:
public class Animal {
public void sound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
public class Cat extends Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
- Abstraction
Abstraction hides complexity, showing only essential features.
Analogy: Driving a car without needing to understand the engine.
Example:
abstract class Vehicle {
abstract void start();
public void stop() {
System.out.println("Vehicle stopped");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car started");
}
}
Summary
Encapsulation: Protect data and expose only what’s necessary.
Inheritance: Share and extend behaviors.
Polymorphism: Same method, different implementations.
Abstraction: Hide complexity, show essentials.
Thanks for reading! Feel free to ask questions or share your thoughts in the comments. Stay tuned for more software engineering tips!
Top comments (0)