In polymorphism, only a derived class can be a base class, what happens here?

In polymorphism, I learned that only a derived class can be a base class, but look at my example, the base class is now a derived class:

static void Main() { Person a = new Customer(); //here a base class is a derived class Customer c = (Customer)a; } class Person { } class Customer : Person { } 

Why is this possible?

Should members of a derived class not be discarded when instantiating in the base class?

If I create a derived class in a base class, is the size of the allocated memory the size of the derived class?

+4
source share
2 answers

Since a is a Client object, this will work just fine. Let me clarify:
a is a "variable" of type Person, it can hold an "object" of any type from Person to any of its child classes.
c is a "variable" of type Client and may contain an "object" of any type from the Client to any of its child classes.

What you did puts the "object" of the Client in the "variable" Person. Wherever you move this object, it will always be a Client object. So, we need to keep in mind that even if you put the โ€œobjectโ€ of the Client in a โ€œvariableโ€ of type Person, the type of the object is still the client. In the following statement, you simply transferred the object to the correct type.

The variable is the same as the basket. It may contain anything less than it. If you pull an object out of the basket and put it in another basket, the object will still remain the same.

+4
source

While the above works (as indicated in other answers), the following will fail, which is likely to cause the base class to fail for the derived class (unless you know the type at runtime).

 static void Main() { Person a = new Customer(); //This will fail at runtime. Programmer c = (Programmer)a; } class Person { } class Customer : Person { } class Programmer: Person { } 
0
source

All Articles