DEV Community

Susan Wangari
Susan Wangari

Posted on

Principles of Object Oriented Programming

Object Oriented Programming involves using objects to model real world things that we want to represent inside our programs.
An object is an instance of a class that has methods and properties.
A class is a blueprint of an object.Classes can have many objects.
Let's take a look at the Principles of Object Oriented Programming
1.Encapsulation
This involves enclosing or hiding something.In an object,the methods and properties are enclosed within the object.An object keeps its state private, inside a class.Other objects don't have direct access to this state.To communicate with the object, you should use the methods provided but you cannot change the state of the object.
for example
class bird {
constructor (name, legs) {
this.name = name;
this.id = id;
}
add_Friends(add) {
this.add = add;
}
getDetails() {
console.log(Name is ${this.name}, Friends is ${this.add});
}
}
let bird1 = new bird("Hooky", 2);
bird1.add_Friends("Batu");
bird1.getDetails();
2.Abstraction
It involves hiding complex details and showing simple ones.It helps code to be more understandable.
for example
function man (fName, lName) {
let firstName = fName;
let lastName = lName;

let getDetails_noaccess = function() {
return (My first name is ${firstName}, my last name is ${lastName});
}

this.getDetails_access = function() {
return (My first name is ${firstName}, my last name is $ {lastName});
}
}
let man1 = new man("Samson", "Tunny");
console.log(man1.firstName);
console.log(man1.getDetails_noaccess);
console.log(man1.getdetails_access());
3.Inheritance
It is gaining something from someone else.In Object Oriented Programming, it allows for parent class to pass functionality to a child class hence avoiding repeats.It uses extends to create a subclass of the object.
for example
class person {
constructor(name) {
this.name = name;
toString() {
return (The name of this person is ${this.name});
}
}
class student extends person {
constructor(name, id) {
super(name);
this.id = id;
}
toString() {
return (
{super.toString()}, Student ID is ${this.id}`);
}
}
let student1 = new student("Nyota", 20);
console.log(student1.toString());
4.Polymorphism
It is something having multiple forms.In Object Oriented Programming, it involves the same method being used on different objects. Polymorphism gives us the ability to call the same method on different objects.Each child keeps its own methods as they are.
for example
class A {
display() {
console.log("A is invoked");
}
}
class B extends A {
display() {
console.log("B is invoked");
}
}
let a = [new A(), new B()];
a.forEach(function(msg) {
msg.display();
});

Conclusion
These principles are what make JavaScript to be an Object Oriented Language.All these principles are meant to create a better understanding and increase the usability of objects.They also help reduce repetition of code hence leading to clean code.

Top comments (0)