Object-Oriented Programming
programming fundamentals paradigm software-design
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a way of writing computer programs by creating reusable pieces called objects. Each object has its own properties (like color or size) and can do specific things (like move or change). This makes it easier to build big programs by using the same objects in different ways.
Simple Analogy
Think of Object-Oriented Programming like building with LEGO blocks:
- Objects: Like individual LEGO blocks. Each block has:
- Properties: Color, size, shape
- Behaviors: How it connects to other blocks
- Classes: Like the instructions for making different types of LEGO blocks.
A “Car” class tells you how to make car blocks, but doesn’t create a specific car until you use it. A “Ford” and a “Honda” are both specific instances of the “Car” class. They share properties such as tires, wheel and engine, but they might be different types of tires, wheels and engines.
Key Concepts
- Class: A blueprint for creating objects (like LEGO instructions)
- Object: An instance of a class (like a specific LEGO block)
- Properties: Data stored inside an object (like a block’s color)
- Methods: Things an object can do (like how a block connects)
- Encapsulation: Keeping an object’s inside details private
- Inheritance: Getting properties and behaviors from parent classes
- Polymorphism: Using the same method name for different behaviors
Example
// A simple OOP example in JavaScript
// Parent Vehicle class
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.isRunning = false;
}
start() {
this.isRunning = true;
console.log('Vehicle started.');
}
stop() {
this.isRunning = false;
console.log('Vehicle stopped.');
}
getInfo() {
return `${this.year} ${this.make} ${this.model}`;
}
}
// Car class inherits from Vehicle
class Car extends Vehicle {
constructor(make, model, year, doors) {
// Call the parent constructor
super(make, model, year);
this.doors = doors;
}
// Override the parent method
start() {
this.isRunning = true;
console.log('Car engine purrs to life.');
}
// Car-specific method
honk() {
console.log('Beep beep!');
}
}
// Creating a car object
const myCar = new Car('Toyota', 'Corolla', 2020, 4);
// Using the car object
console.log(myCar.getInfo()); // "2020 Toyota Corolla"
myCar.start(); // "Car engine purrs to life."
myCar.honk(); // "Beep beep!"