Object Oriented Programming (OOP)
Object-oriented programming is a programming paradigm based on the concept of objects.
Key Principles of OOP
1.Encapsulation:
- Groups related variables and functions into an object.
- Encourages fewer parameters in functions, reducing complexity. Example:
function Circle(radius) {
this.radius = radius;
this.draw = function() {
console.log('draw');
};
}
const circle = new Circle(5);
console.log(circle.radius); // Access encapsulated property
circle.draw(); // Call encapsulated method
2.Abstraction:
Hides the details and complexity, exposing only necessary parts of an object.
Simplifies the interface and reduces the impact of changes in the underlying code.
Example: Abstracting methods while hiding internal logic.
3.Inheritance:
Allows a class (child) to inherit properties and methods from another class (parent).
Reduces redundant code.
Example:
class Animal {
eat() {
console.log("This animal is eating.");
}
}
class Dog extends Animal {
bark() {
console.log("The dog is barking.");
}
}
const dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark();
4.Polymorphism:
Refers to objects taking many forms.
Allows a unified interface for different object types, enabling code reuse and flexibility.
Example:
class Animal {
sound() {
console.log("This animal makes a sound.");
}
}
class Dog extends Animal {
sound() {
console.log("The dog barks.");
}
}
const animal = new Animal();
const dog = new Dog();
animal.sound(); // Output: This animal makes a sound.
dog.sound(); // Output: The dog barks.
Importance of OOP
- Encapsulation: Reduces complexity and enhances reusability.
- Abstraction: Hides implementation details, simplifying interaction.
- Inheritance: Eliminates code duplication and promotes reuse.
- Polymorphism: Enables flexibility and streamlined code structures.
Practical Examples
Classes and Constructors
- Structured, clean way to create objects.
- Example:
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
displayProduct() {
console.log(`Product: ${this.name}`);
console.log(`Price: $${this.price.toFixed(2)}`);
}
calculateTotal(salesTax) {
return this.price + this.price * salesTax;
}
}
const product1 = new Product("Laptop", 1200);
product1.displayProduct();
console.log(`Total Price: $${product1.calculateTotal(0.1).toFixed(2)}`);
Inheritance with Animals
- Demonstrates reusability and method overriding.
- Example:
class Animal {
eat() {
console.log("This animal eats food.");
}
}
class Bird extends Animal {
fly() {
console.log("This bird can fly.");
}
}
const bird = new Bird();
bird.eat();
bird.fly();
Reflection
What I Learned:
- Core OOP principles: Encapsulation, Abstraction, Inheritance, Polymorphism.
- Practical use cases for reducing code complexity and enhancing reusability.
- Applying constructors, methods, and inheritance to solve real-world problems.
OOP is another level.
We go again tomorrow!
Top comments (0)