A
A
aaltw2021-08-11 17:31:43
OOP
aaltw, 2021-08-11 17:31:43

Why is a class object created through a parent class?

https://www.w3schools.com/cs/cs_polymorphism.php

This tutorial talks about polymorphism and provides examples. In one of the following happens:

Animal myAnimal = new Animal();  // Create a Animal object
Animal myPig = new Pig();  // Create a Pig object
Animal myDog = new Dog();  // Create a Dog object

After that, they supplement that the methods were not overridden and that virtual and override should be used.

I tried changing object creation to normal:
Animal myAnimal = new Animal();  // Create a Animal object
Pig myPig = new Pig();  // Create a Pig object
Dog myDog = new Dog();  // Create a Dog object

And everything works as it should, with an override.

What for generally creation of object through the parent can be necessary?
Parent myChild = new MyChild( );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-08-11
@altw

It's not "creating an object through a parent". Creation is the same in all cases. Here, a reference to the child is stored in a variable of the parent's type. This, like, is dynamic polymorphism. The point is that you can put different, not predetermined children into a collection with a parent type, for example. Or accept and return from methods - also a parent, not specific children.
What for? For example, you have a cell object that contains an animal. Conventionally, you should not make different cages - PigCage, DogCage, CatCage, but should use one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question