Abstraction-tutorial
Abstraction is one of the core concepts of object-oriented programming (OOP).
In JavaScript, abstraction means hiding complex details and showing only the essential features of an object.
This helps to
This helps to
- Make code simpler and easier to understand
- Protect important data
- Focus on what an object should do, instead of how it does it
How Abstraction Works in JavaScript
Unlike some other languages like Java or C#, JavaScript doesn’t have built-in support for abstract classes.
However, you can simulate abstraction using:
Unlike some other languages like Java or C#, JavaScript doesn’t have built-in support for abstract classes.
However, you can simulate abstraction using:
- Prototype inheritance
- Constructor functions
- Throwing errors to prevent direct instantiation
Example: Abstraction with Constructor Function
In the example below
Output
.webp)
In the example below
- We create an abstract class Vehicle that cannot be instantiated directly.
- We then create a subclass Bike that inherits from Vehicle and implements its own details.
<!DOCTYPE html><html>
<body>
<script> // Creating abstract class Vehicle function Vehicle() { this.vehicleName = "vehicleName"; throw new Error("You cannot create an instance of Abstract Class"); }
Vehicle.prototype.display = function () { return "Vehicle is: " + this.vehicleName; }
// Subclass Bike inheriting from Vehicle function Bike(vehicleName) { this.vehicleName = vehicleName; }
// Linking prototypes Bike.prototype = Object.create(Vehicle.prototype);
// Creating an instance of Bike var bike = new Bike("Honda");
document.writeln(bike.display()); </script>
</body>
</html>
Output
.webp)
Explanation
- We simulate abstraction by making the Vehicle constructor throw an error.
- This ensures that developers cannot create an object directly from Vehicle.
- Instead, you must create an object from a subclass like Bike which inherits the common properties and methods from Vehicle.
Key Point
- Abstraction hides unnecessary complexity.
- Helps developers focus only on relevant properties and methods.
- JavaScript uses prototype-based inheritance and constructor functions to implement abstraction.