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:
class Parent {
greet() {
console.log('Hello from Parent');
}
}
class Child extends Parent {
// Method override
greet() {
console.log('Hello from Child');
}
}
const child = new Child();
child.greet(); // prints: Hello from Child
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!