Is overriding setter or getter considered polymorphism in js

Viewed 24

Let's say I have a class Person like so:

class Person{
 constructor(name){
  this._name = name;
 }
 get name(){
  return this._name;
 }
}

And I also have a class Worker that inherits from class Person like so:

class Worker extends Person{
 constructor(name, job){
  super(name);
  this._job=job;
 }
 get job(){
  return this._job;
 }
 get name(){
  return "Worker: " + this._name;
 }
}

Is overriding name getter in Worker class considerd polymorphism in javascript?

1 Answers

Polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types. http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf

It means that you can say that something is polymorphism if your behavior is various depends on type.

So if you have a class A and was extended by two other classes B and C, and inside the B and C classes you have overridden some method of class A. It means that if you will have a list of objects that are instances of class A (or class that inherit class A) and call the overridden method, you will see different behavior for the same method depend on with specific instance of A class you have.

Others think that if you are using strong typing language, you can have the same various based on types of method attribute. And in this case it still polymorphism. All methods in the same class, but they are overloaded.

So if thinking about classic polymorphism definition and how we can use it in JS it means that we can have third way of realization it's create one method that will call other methods depend on type of parameters. It can be simple method, and it will be emulation of polymorphism. But for the client code it will look exactly like polymorphism with overloading.

Based on those 3 ways to using polymorphism, we can have a conclusion that to be sure what is actually polymorphism and what is not, we should see to the client code as well.

Related