JavaScript Class Inheritance
Class inheritance in JavaScript allows one class to inherit properties and methods from another class. This enables code reusability and a structured approach to object-oriented programming.
🔹 How to Inherit a Class? (extends
)
The extends
keyword is used to create a child class that inherits from a parent class.
✅ Basic Example of Inheritance
✔ The Dog
class inherits the name
property and makeSound()
method from Animal
.
✔ The bark()
method is unique to Dog
.
🔹 Calling Parent Class Constructor (super
)
If a child class has its own constructor
, it must call super()
to invoke the parent class constructor.
✅ Example: Using super()
✔ super(name)
ensures name
is initialized from the Animal
class.
✔ The Dog
class adds a new property breed
.
🔹 Overriding Methods
A child class can override a parent method by defining the same method name.
✅ Example: Overriding a Method
✔ The Dog
class overrides the makeSound()
method from Animal
.
🔹 Calling Parent Methods Using super
You can still call a parent method inside an overridden method using super.methodName()
.
✅ Example: Using super.methodName()
✔ super.makeSound()
calls the original method from the parent class.
✔ The child class extends the behavior rather than replacing it.
🔹 Static Methods & Inheritance
Static methods belong to the class itself, not instances. They are inherited by child classes.
✅ Example: Static Methods in Inheritance
✔ Dog
inherits the generalInfo()
method from Animal
.
🎯 Summary
✔ Use extends
to create a child class.
✔ Use super()
in the constructor to call the parent class constructor.
✔ Methods can be overridden in child classes.
✔ Use super.methodName()
to call the parent method inside an overridden method.
✔ Static methods are inherited by child classes.
🚀 Want more examples? Let me know! 😊