S
S
Stepan2014-08-08 20:49:31
JavaScript
Stepan, 2014-08-08 20:49:31

Explain what polymorphism is in simple terms?

And a simple example (preferably in JS)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Deerenaros, 2014-08-08
@xoma2

Okay guys. Enough already, why such difficulties? We take and read . In general, it is not at all necessary to read about architecture and abstractions in your own language, although javascript was born a freak in this regard.
OK. Polymorphism should never be considered in isolation from other fundamental concepts - abstraction, encapsulation and inheritance. The object and the like are attached from the axioms (although these are also axioms).
Actually, imagine a glass, a mug, a kettle, a coffee machine, a bicycle and a skate nearby. What do they all have in common? Well, at least what they are. That is, these are the objects that have been created. But how were they created? Most likely at the manufacturer's drawings. Ok, let's call the constructor a drawing. Well, what about the class? And what is it? And it is not in our universe - this essence is an abstraction that lives only in our thoughts. In the real world, it does not exist and never will, such is physics - it does not care that birds and mammals have distant relatives - it only provides the possibility of natural selection. And we, people, find relatives to each other.
We figured out the objects and classes, but what about our glasses and bicycles. We have already understood that everything is an object, that is, roughly, all objects can be inherited from some superancestor, superclass, which is implemented in some languages. But what else is there in common between a skateboard and a glass, for example? Of course, you can go deeper and consider that they are all from molecules, and they are all from solids. However, this is all nonsense and SPGS , so the answer is simple - nothing. That is, they are completely different objects with completely different functionality. Moreover, of course, computer models and hierarchies will be very different from physicists and chemists. And this is normal, the question of the adequacy of models is raised only when the model is inadequate, and until then you can cut anything, as long as it works.
Here. We have a super-ancestor of Object, from which all objects are inherited by default. Assume that objects are made up of atoms and that is what all objects inherit. But all additions and edits are polymorphism. So, we made wheels out of atoms and attached them to the board - ok, this is a skateboard. You can stand up and roll on it, and dodge strongly and fly three meters above the ground, just radiating your bright ego. While a glass is we molded a dense container from atoms, from which water does not pour out under the influence of gravity. And the direct use of the glass is to pour water over the mouth so that the water flows straight into the stomach. That's what real boys do, not caring about hiccups or fear of drowning, so here's polymorphism.
However, what about the rest? We also have abstraction, encapsulation and inheritance. Ok, let's start with inheritance, since it is the closest. What do we have in common between a glass and a mug? Well, you can pour water into both, but the mug has a handle to hold on to. That is, you can come up with a certain general class - capacity. However, what is this class? For example, you can take a glass for this class, then all containers are default glasses, and everything else is modified glasses. But someone likes jugs more, for example, some chicks put them on their heads, considering it convenient. Well, let them wear it, but somehow it is necessary to decide what is more important and ideal. So - the unattainable ideal is the main one - this is called an abstract class. That is, a container that cannot be created, for which there is no complete drawing. And all the drawings that have been completed to the full are classes inherited from the capacity class.
Here we come to abstraction. This kind of hierarchical inheritance brings us to perhaps the main idea of ​​OOP. So we took and singled out everything where you can pour water into a separate class, drew a general drawing, but didn’t finish it on purpose, leaving a gap for future creators, and called the drawing - capacity. Thousands of years have invented all the worlds create their own containers, one better than the other. For different people - in different ways, of course. But each time grouping glass molecules in a certain way is not an easy task. Therefore, the artisans went to the trick, they created a secret council of artisans of the world and decided to share their achievements with each other. That is, create small drawings and declare a class, for example, a twisted pen in the form of a Mobius strip, for example. Perhaps such a pen is convenient only for alien creatures, but the drawing is created and can be referenced when creating your drawing. Thus, we abstract from the low-level task of "forming containers by moving molecules" to "constructing a container by combining parts, elements." This is abstraction.
But we come to the last point - encapsulation. It is inseparable from abstraction, and in fact thanks to it it works. Encapsulation is a kind of glue (or blue tape) that sticks different drawings into one. That is, the combination of parts to create your own - this is encapsulation. Moreover, when combining, we can not describe the details of this combination (that is, class members can be private), thus helping those who use this drawing to abstract. Let's look at the teapot - what is it? This is a glass (or mug) to which a heating element is glued from below (or maybe inside in the middle?). By passing a current through it, according to Ohm's law encapsulated in the heating element, heat will be released and water will be heated. And the coffee machine? This is a much more complex device, with many pumps, tanks, locks, grinders and kettles. And it's all glued on. Maybe blue duct tape. This is again encapsulation.
Thus, abstraction is impossible without encapsulation and inheritance, just as polymorphism is impossible without, in fact, inheritance. Well, polymorphism is also impossible without encapsulation, which is tritely useless without inheritance and polymorphism. These are the triangles with pies. It's a pity they lied about the pie. And about the birthday.

E
Evgeny Petrov, 2014-08-09
@Petroveg

I'm in shock, to be honest... That's how the questions about OOP in Javascript begin, so hands to feet and away we go... Who is Java, who is C # gives examples. and even footcloths harsh. And each postscript makes - they say, in Javascript it is not so clear.
That is, a person who studies Javascript, and has never seen other languages, immediately nods happily at the sight of unfamiliar syntax? Are you really full of faith in such a bright ending?
I'll ask everyone who answers:
1. Number.prototype.toString() and Object.prototype.toString() - is it polymorphism or not?
2. Date.prototype.hasOwnProperty() and Object.prototype.hasOwnProperty() - is it inheritance or not?
3. What is the difference between them then?
PySy. And I also want to ask all experts in any language other than the one indicated in the question - if in topics with Python, Ruby, PHP, C # tags I start scribbling pieces of code in Javascript, because it seems to me that it’s clearer as soon as those subscribed to these tags ask me ban?

A
Artem Lisovsky, 2014-08-08
@torrie

www.cyberguru.ru/web/html/javascript-introduction-...

..

//Конструктор родительского класса
function Animal(name)
{
  this.name = name;
}

Animal.prototype.speak = function()
{
  alert(this.name + " says:");
}

//Конструктор унаследованного класса "Dog"
function Dog(name)
{
  Animal.call(this, name);
}

Dog.prototype.speak = function()
{
  Animal.prototype.speak.call(this);
  
  alert("woof");
}

//Конструктор унаследованного класса "Cat"
function Cat(name)
{
  Animal.call(this, name);
}

Cat.prototype.speak = function()
{
  Animal.prototype.speak.call(this);
  
  alert("miaow");
}

..

If we call the speak method, it is set in the prototype, and we can use it both from a dog and from a cat. We get the actions of the prototype and then the overridden execution of the method for each inherited element.
var d = new Dog("Fido");     //Создает экземпляр Dog
d.speak();                   //Вызывает функцию speak() класса Dog
 
var c = new Cat("Lucy");     //Создает экземпляр Cat
c.speak();                   //Вызывает функцию speak() класса Cat

There will be "Fido says: woof" and "Lucy says: meow"

S
Shetani, 2014-08-08
@Shetani

Article on the topic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question