Chapter 13: Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data and methods. It is a powerful way to design and structure your code to make it more modular, reusable, and maintainable. This chapter covers the fundamental concepts of OOP, including classes, inheritance, polymorphism, encapsulation, and abstraction.
Classes and Constructors
Classes
A class is a blueprint for creating objects. It defines a set of properties and methods that the created objects (instances) will have.
Syntax:
class ClassName {
constructor(parameters) {
// Initialization code
}
method() {
// Method code
}
}
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`
);
}
}
let person1 = new Person("Alice", 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
Constructors
The constructor is a special method used to initialize objects. It is called when a new instance of the class is created.
Example:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Car make: ${this.make}, model: ${this.model}`);
}
}
let myCar = new Car("Toyota", "Corolla");
myCar.displayInfo(); // Output: Car make: Toyota, model: Corolla
Inheritance
Inheritance allows one class (the child class) to inherit properties and methods from another class (the parent class). This promotes code reuse and establishes a natural hierarchy.
Syntax:
class ChildClass extends ParentClass {
// Additional properties and methods
}
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let myDog = new Dog("Rover");
myDog.speak(); // Output: Rover barks.
Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon. In JavaScript, this is often achieved through method overriding.
Example:
class Bird {
speak() {
console.log("Tweet tweet");
}
}
class Sparrow extends Bird {
speak() {
console.log("Chirp chirp");
}
}
let bird = new Bird();
let sparrow = new Sparrow();
bird.speak(); // Output: Tweet tweet
sparrow.speak(); // Output: Chirp chirp
Encapsulation
Encapsulation is the practice of hiding the internal state and requiring all interaction to be performed through an object's methods. This protects the internal state from unintended modifications and makes the class easier to use.
Example:
class BankAccount {
#balance; // Private field
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
}
}
getBalance() {
return this.#balance;
}
}
let account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // Output: 1300
Abstraction
Abstraction involves hiding complex implementation details and showing only the necessary features of an object. This simplifies the use of objects and reduces complexity.
Example:
class Shape {
constructor(type) {
this.type = type;
}
draw() {
console.log(`Drawing a ${this.type}`);
}
}
class Circle extends Shape {
constructor(radius) {
super("Circle");
this.radius = radius;
}
draw() {
console.log(`Drawing a ${this.type} with radius ${this.radius}`);
}
}
let circle = new Circle(10);
circle.draw(); // Output: Drawing a Circle with radius 10
Summary
In this chapter, you learned the core concepts of Object-Oriented Programming (OOP), including:
- Classes and Constructors: How to define and use classes and constructors to create objects.
- Inheritance: How to create child classes that inherit from parent classes, promoting code reuse.
- Polymorphism: How to override methods in child classes to provide different implementations.
- Encapsulation: How to protect an object's internal state and expose only necessary methods.
- Abstraction: How to simplify complex systems by exposing only the relevant features of an object.
These OOP principles help you write more organized, modular, and maintainable code by creating well-defined structures and relationships between objects.