Fundamentals of Object Oriented Programming
OOP is a programming paradigm based on the concepts of objects. They are meant to be flexible, easy to maintain and organized for a better coding experience among a team of developers. In OOP, objects are self-contained pieces or blocks of code.
They are simply building blocks of applications that interact with one another. These interactions happen through a public interface(API), methods that the code outside of the object can access and use to communicate with the object.
For this tutorial, I will use ES6 classes which are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.
There are four fundamentals of OOP usually abbreviated as APIE;
We focus on the essential qualities of something rather than one specific example. This comes with a number of advantages like;
. Helps the user to avoid writing low level code.
- Avoids code duplication and increases reusability.
- Can change internal implementation of class independently without affecting the user.
Lets take an example;
We should be able to return a deposit of 2000, and a withdraw 0f -500
a child class can override a method it inherited from a parent class. For instance in the example below a car with an accelerate method can go at speeds of + 10 but its child class tesla can ever go at speeds of +20;
This makes all properties and methods of a certain class available to a child class forming a hierarchical relationship between classes. This allows us to reuse common logic and to model real-world relationships for example;
Inheritance is shown by the extends keyword with the child class on the left and the parent class on the right. You may not need a constructor if you do not have any new properties.
And finally encapsulation, it contains elements of an object ,not just keeping them together but also protect them.
Object should not make anything about itself available except when its absolutely necessary for other parts of the application to work. For example a bank app, the method to request a loan should not be accessed outside the class or even ones pin number