Answer the question
In order to leave comments, you need to log in
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
Animal myAnimal = new Animal(); // Create a Animal object
Pig myPig = new Pig(); // Create a Pig object
Dog myDog = new Dog(); // Create a Dog object
Parent myChild = new MyChild( );
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question