In this chapter, we will learn about Object-Oriented Programming (OOP) in JavaScript. OOP is a programming paradigm based on the concept of "objects," which can contain data and code to manipulate that data. We will cover:
- What is OOP?
- Basic Concepts of OOP
- Creating Classes
- Constructor Method
- Creating Objects
- Adding Methods to a Class
- Inheritance
- Encapsulation
- Polymorphism
- Simple Programs using OOP Concepts
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods to manipulate that data. OOP is based on several key concepts, including classes, objects, inheritance, encapsulation, and polymorphism.
Basic Concepts of OOP
- Class: A blueprint for creating objects. A class defines properties and methods that the created objects will have.
- Object: An instance of a class. Objects have properties and methods defined by their class.
- Inheritance: A mechanism by which one class can inherit properties and methods from another class.
- Encapsulation: The practice of keeping data and methods within a class, and controlling access to them.
- Polymorphism: The ability to use a single method name for different types of objects.
Creating Classes
In JavaScript, classes can be created using the class
keyword.
Syntax
class ClassName {
constructor(parameters) {
// Initialize properties
}
// Methods
}
Example
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
Creating Objects
You can create objects from a class using the new
keyword.
Example
let person1 = new Person("Amit", "Kumar", 25);
let person2 = new Person("Ramesh", "Fadatare", 30);
console.log(person1);
console.log(person2);
Output:
Person { firstName: 'Amit', lastName: 'Kumar', age: 25 }
Person { firstName: 'Ramesh', lastName: 'Fadatare', age: 30 }
Adding Methods to a Class
Methods can be added to a class to define behaviors for the objects.
Example
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// Method to get full name
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
let person = new Person("Amit", "Kumar", 25);
console.log(person.getFullName());
Output:
Amit Kumar
Inheritance
Inheritance allows a class to inherit properties and methods from another class. In JavaScript, inheritance is implemented using the extends
keyword.
Example
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
class Student extends Person {
constructor(firstName, lastName, age, course) {
super(firstName, lastName, age);
this.course = course;
}
getCourse() {
return this.course;
}
}
let student = new Student("Ramesh", "Fadatare", 20, "Engineering");
console.log(student.getFullName());
console.log(student.getCourse());
Output:
Ramesh Fadatare
Engineering
Encapsulation
Encapsulation is the practice of keeping data and methods within a class, and controlling access to them. In JavaScript, you can use the #
symbol to create private fields.
Example
class Person {
#ssn;
constructor(firstName, lastName, age, ssn) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.#ssn = ssn;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
getSSN() {
return this.#ssn;
}
}
let person = new Person("Amit", "Kumar", 25, "123-45-6789");
console.log(person.getFullName());
console.log(person.getSSN());
Output:
Amit Kumar
123-45-6789
Polymorphism
Polymorphism allows you to use a single method name for different types of objects. In JavaScript, this can be achieved through method overriding.
Example
class Animal {
makeSound() {
return "Some generic sound";
}
}
class Dog extends Animal {
makeSound() {
return "Bark";
}
}
class Cat extends Animal {
makeSound() {
return "Meow";
}
}
let dog = new Dog();
let cat = new Cat();
console.log(dog.makeSound());
console.log(cat.makeSound());
Output:
Bark
Meow
Simple Programs using OOP Concepts
Program 1: Bank Account
class BankAccount {
constructor(accountNumber, accountHolder, balance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (amount > this.balance) {
console.log("Insufficient funds");
} else {
this.balance -= amount;
}
}
getBalance() {
return this.balance;
}
}
let account = new BankAccount("1234567890", "Rahul Fadatare", 5000);
account.deposit(2000);
account.withdraw(1000);
console.log("Balance:", account.getBalance());
Output:
Balance: 6000
Program 2: Library Management
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
getDetails() {
return `${this.title} by ${this.author}, ISBN: ${this.isbn}`;
}
}
class Library {
constructor() {
this.books = [];
}
addBook(book) {
this.books.push(book);
}
removeBook(isbn) {
this.books = this.books.filter(book => book.isbn !== isbn);
}
getBooks() {
return this.books.map(book => book.getDetails());
}
}
let library = new Library();
let book1 = new Book("The Alchemist", "Paulo Coelho", "123456");
let book2 = new Book("The Monk Who Sold His Ferrari", "Robin Fadatare", "789101");
library.addBook(book1);
library.addBook(book2);
library.removeBook("123456");
console.log(library.getBooks());
Output:
["The Monk Who Sold His Ferrari by Robin Fadatare, ISBN: 789101"]
Program 3: Employee Management
class Employee {
constructor(name, position, salary) {
this.name = name;
this.position = position;
this.salary = salary;
}
getDetails() {
return `${this.name}, ${this.position}, Salary: ${this.salary}`;
}
}
class Manager extends Employee {
constructor(name, position, salary, department) {
super(name, position, salary);
this.department = department;
}
getDetails() {
return `${super.getDetails()}, Department: ${this.department}`;
}
}
let emp1 = new Employee("Amit Kumar", "Developer", 50000);
let emp2 = new Manager("Ramesh Fadatare", "Manager", 80000, "IT");
console.log(emp1.getDetails());
console.log(emp2.getDetails());
Output:
Amit Kumar, Developer, Salary: 50000
Ramesh Fadatare, Manager, Salary: 80000, Department: IT
Conclusion
In this chapter, you learned about Object-Oriented Programming (OOP) in JavaScript, including the basic concepts, creating classes and objects, adding methods, inheritance, encapsulation, and polymorphism. We also provided various use cases with simple programs to demonstrate the usage of OOP concepts. OOP is a powerful paradigm that helps you organize and manage your code better.