S
S
Student Hard Worker2021-07-27 18:57:31
OOP
Student Hard Worker, 2021-07-27 18:57:31

What is polymorphism here?

Hello, I got confused with the concept of "polymorphism", I always perceived it as - "the ability to use the members of an object regardless of its type", i.e.:

class A {
  public virtual string Name { get; init; } = "A";
}

class B : A {
  public virtual string Name {get; init;} = "B";
}

...
A a = new A();
B b = new B();

a.Name; // A
b.Name; // B
((A)b).Name; //B


That is, despite the fact that Bwe cast the type to the base type , Athe member of the object Nameis still called onB
Polymorphism (polymorphism) - the ability of the same variable at different points in the execution of the program to designate objects of different types (classes) belonging to the same base type (class or interface).

ie:
Virtual class members - do all the magic for polymorphism?

But something confused me, and somewhere I heard another interpretation, polymorphism - to use the members of an object based on its type, which seems to me not entirely correct.

What is polymorphism in the end?
Googled, watched a video, abstract classes everywhere, some kind of php, explanation on Animal, Dog, Cat, but there is no simple and capacious explanation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2021-07-27
@EugeneTypescript

It is easy to get confused in the term "polymorphism". Because the term has many meanings.
In your example, I would argue like this:
polymorphism = poly + morphos
poly = many
morphos = form
, that is, polymorphism means "many forms"
We have a class A, it has a Name property. When we use the virtual keyword, we are saying that for all the types that A has, the Name property can have many different forms.
When we inherit B from A and override the Name property, we are defining another form.
The Name property, depending on the type, will have a specific form, one of many forms.
This is polymorphism.
This is Zen.)

S
snake2, 2021-07-27
@snake2

There is a good article about OOP here on Habré
https://habr.com/en/post/87205/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question