Greetings, coder! Our voyage into Object-Oriented Programming (OOP) continues. Today, we will cover Inheritance, which can make our code more efficient and tidy.
Just as children inherit traits from their parents, child
classes in programming inherit behaviors and properties from parent
classes.
Below is a practical example displaying a child
class inheriting from a parent
class:
In this example, Child
inherits from Parent
, so it shares the greet()
method, making our code smarter!
To implement inheritance, we introduce a keyword: 'extends'. This powerful keyword allows a new class to inherit properties and methods from an existing class. Let's say, a 'child' class 'extends' from the 'parent' class.
Let's see how a car
can extend a vehicle
. Both are entities with the potential for motion, but a car
offers additional specific features — such as wheels.
In this code, the Car
class extends from the Vehicle
class, sharing the move()
method.
The super
keyword calls the parent class's constructor and provides access to its properties and methods. Let's consider a real-life instance of an apple inheriting from a fruit.
Here, in the Apple
class, super
calls the constructor of the Fruit
class to inherit the name
property. If the child's Apple
class does not have any constructor, JavaScript will automatically call the parent's constructor when creating an instance of the Apple
class.
During inheritance, there may be instances where a child
class needs a different behavior for a method than what the parent
class provides. That's where method redefinition, also known as method overriding, comes into play.
Method overriding allows a child
class to provide a different implementation of a method that is already defined by its parent
class. By using the same method name, with the same parameters in the child
class, the parent
class's method will be overridden.
Here's a practical example:
In the code above, the Child
class overrides the greet()
method of Parent
. When we call the greet()
method on an instance of Child
, the message from the Child
class is printed, not from the Parent
class.
It's a Flexibility feature of OOP that allows us to make our classes more specific and fitting for their intended use. Always handle with care — respect the intended use of inherited methods and make sure your updated method suits your class's needs!
Excellent work! Today, we've mastered inheritance in JavaScript, noted how properties and methods pass from the parent to the child class via extends
, and understood how super
connects a child class with its parent class.
Up next are engaging practice exercises where you'll implement classes related to real-world scenarios. Remember, practice makes perfect! Stay motivated, and good luck with your coding journey!
