Answer the question
In order to leave comments, you need to log in
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
B
we cast the type to the base type , A
the member of the object Name
is 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).
Answer the question
In order to leave comments, you need to log in
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.)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question