What is OOP? - Object-Oriented Programming Explained
Question:
What is OOP? (Fundamental knowledge)
Answer:
OOP stands for object-oriented programming. It means organizing code in a structured way around objects.
Take a simple example: if you have a user object, it can hold functions and properties like login(), name, and payBy().
If we don’t organize code by object, everything gets mixed together. That coupling makes the code harder to maintain, modify, and read.
If we structure it around a user object:
class user {
userName: string;
login() {}
payBy(whichBank: string) {
if (whichBank === "momo")
...
}
}
then we’d call it like user.userName = "Khoa" and user.login().
Encapsulation
The code is easier to read because those functions belong to that specific object and only expose what needs to be used from the outside. The internal logic stays protected.
- Child classes can reuse parent classes and reduce duplication:
class engine {
howManyOilPerKm() {}
}
class car {
engine: engine;
run() {}
}
This reduces duplication, but it can also create tight coupling. If the parent class changes, the child class may break too.
Polymorphism
Addition is a simple example of polymorphism. We can have a basic add() function, but when we pass different types such as integers or decimals, the object can handle them in different ways. That is polymorphism. It does not mean using if and else everywhere. For example:
interface Add {
sum(first: number, second: number): number;
}
class AddNumber implements Add {
sum(first: number, second: number): number {
return Math.round(first + second);
}
}
class AddFloat implements Add {
sum(first: number, second: number): number {
return first + second;
}
}
function addThreeArgument(adder: Add, first: number, second: number, third: number): number {
return adder.sum(adder.sum(first, second), third);
}
const numberAdder = new AddNumber();
const floatAdder = new AddFloat();
addThreeArgument(numberAdder, 1, 2, 3);
addThreeArgument(floatAdder, 1.1, 2.2, 3.3);
In short, one object can take multiple forms, and the right one is chosen based on type without manual checks.
It also makes logging and debugging easier, because you can check which class is actually involved without stuffing the logic into a long if/else chain that is harder to mock and test.