Polymorphism is a fundamental concept in object-oriented programming. It allows objects of different types to be treated as objects of a common, more generalized type. This enables the use of a single interface to represent different types of entities, thereby facilitating code reusability and modularity. Understanding and effectively using polymorphism can lead to more efficient and maintainable code structures.
In JavaScript, you can override an inherited method, which facilitates polymorphism.
class CourseAssistant {
getBaseSalary() {
return 500.0; // dollars
}
getHourlyPayRate() {
return 15.0; // dollars
}
}
class ExperiencedCourseAssistant extends CourseAssistant {
/* overrides */
getHourlyPayRate() {
return 1.1 * super.getHourlyPayRate();
}
}
function calcPayment(courseAssistant, hoursWorked) {
let wages =
courseAssistant.getBaseSalary() +
hoursWorked * courseAssistant.getHourlyPayRate(); /* dynamic dispatch */
console.log(wages);
}
const tom = new CourseAssistant();
const mona = new ExperiencedCourseAssistant();
calcPayment(tom, 10); // Output: 650
calcPayment(mona, 10); // Output: 665
In the example above, getHourlyPayRate()
is dispatched based on the actual type of the courseAssistant
argument. The system decides at runtime whether to dispatch the overridden getHourlyPayRate()
, which demonstrates dynamic polymorphic behavior.
Method overriding in JavaScript allows methods with the same name to exist in both parent and subclasses.
Note: JavaScript does not support method overloading because a method can accept fewer or more arguments than its declared parameters.