Abstraction
What is Abstraction?
Abstraction is the concept of hiding complex internal workings and showing only the essential features of an object to the outside world.
When you drive a car, you use the steering wheel and the pedals. You don't need to know how the fuel injector mixes air and gas, or how the transmission shifts gears. The car "abstracts" away that complexity and gives you a simple interface.
Abstraction in JavaScript
Unlike languages like Java or C#, JavaScript does not have a built-in abstract keyword. However, we can achieve abstraction using encapsulation (hiding private variables and methods) and providing a simple public interface.
class CoffeeMachine {
#waterAmount = 0; // Private field
// Private method simulating complex internal logic
#boilWater() {
console.log("Boiling water to 100 degrees...");
}
// Private method
#brewCoffee() {
console.log("Brewing the coffee grounds...");
}
// Public Interface - This is all the user sees!
makeCoffee(amount) {
this.#waterAmount = amount;
this.#boilWater();
this.#brewCoffee();
console.log(`☕ Here is your ${amount}ml coffee!`);
}
}
const machine = new CoffeeMachine();
// The user just presses a button (calls a simple method)
machine.makeCoffee(250);
In the example above, the user of the CoffeeMachine only needs to know about the makeCoffee() method. They are completely blocked from calling #boilWater() directly, which protects the system from breaking.
Why use Abstraction?
- Simplicity: It makes your classes much easier to use because other developers only interact with a few simple public methods.
- Safety: By hiding complex logic, you prevent accidental interference from other parts of the code.
- Flexibility: You can completely rewrite the internal
#boilWaterlogic later, and it won't break the code for anyone calling the publicmakeCoffee()method!
💡 Himanshu's Tip:
A good rule of thumb for designing classes: Make everything private by default (#), and only make a method public if it is absolutely necessary for the outside world to interact with it!
Interview Questions
- What is the purpose of Abstraction in OOP?
- Does JavaScript have an
abstractkeyword like Java? How do we simulate it? - Give a real-world example of abstraction (other than a car or coffee machine).