Object Oriented Programming(part 2) : Every JavaScript developer must know
Object oriented programming is a programming language paradigm that is based on the concept of objects
- which can contain data in the form of properties and code in the form of methods.
- OOPs is a popular programming paradigm because it allows for modular, reusable code that is easier to maintain, read and scale.
Features of OOPS
There are four rules or main pillars of object oriented programming language. This defines how the data and actions associated with the data are organized using code.
OOPS concepts
- Objects
- classes
- inheritance
- polymorphism
- encapsulation
- abstraction
We will discuss point 3 to point 6 in this blog.
Inheritance
Inheritance is the concept where one class inherits the properties and methods from another class.
In javascript inheritance is achieved through extends keyword.
class animal {
constructor(name){
this.name = name;
}
getName(){
console.log(`${this.name} is an animal`)
}
}
class cat extends animal {
constructor(name, age){
super(name)
this.age = age;
}
getDetails(){
console.log(`${this.name} is ${this.age} years old`)
}
}
const myCat = new cat('snowbell', 2)
myCat.getName(); //snowbell is an animal
myCat.getDetails(); // snowbell is 2 years old
Polymorphism
Polymorphism is the ability of objects to use the same functios in different forms.
- This reduces repetition and makes the code snippet useful in many different cases.
- In javascript it is achieved through method overriding and method overloading.
- Method overriding is where a subclass provides its own implementations of a method that are already declared in parent class.
- Method overloading is where a class has multiple methods of the same name but different parameters.
class shapes{
constructor(color){
this.color = color;
}
draw(){
console.log('Drawing a shape')
}
}
class square extends shapes {
draw(){
console.log(`Drawing a ${this.color} circle`)
}
}
Abstraction
Abstraction is the process of hiding the implementation details while showing only the necessary information to the user.
Encapsulation
It is the practice of hiding the internal details of an object from the outside world.
class wallet{
#balance = 0;
constructor(initbal) {
this.#balance = initbal;
}
getBalance() {
return this.#balance;
}
}
const iwallet = new wallet(100);
console.log(iwallet.getBalance())
By encapsulating the #balance field within the wallet class we are preventing direct access to the #balance field from outside of the class.
This is an example of how encapsulation can help to prevent unwanted modifications in a real-world scenario such as managing a wallet
If you liked my blog, please do follow me on Rhea RB
Thank you for reading ! Happy Coding !!