Please what is the difference between... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please what is the difference between...

The objects: Animal dog = new Dog(); And Dog dog = new Dog(); Considering that the Dog class is a child of the Animal class. Thanks in advance!!!

22nd Oct 2022, 11:53 AM
Mr Ajiero
Mr Ajiero - avatar
2 Answers
+ 5
Inheritance from abstract class, is a form of dynamic polymorphism. https://www.tutorialspoint.com/csharp/csharp_polymorphism.htm This means that the new Dog() instance can behave differently at runtime, depending on the perspective of which class we are looking, the parent class or subclass. This can be interesting if you have multiple subclasses, for example you have a Cat class that also inherits from Animal. In this case you can make an Animal[] array that contains both dogs and cats. Animal dog = new Dog(); Animal cat = new Cat(); Animal[] animals = { dog, cat }; You can invoke any method on each element of this array, which is defined in the parent class Animal. If you are looking at a Dog element, and you want to use one of the methods that is only defined on the Dog subclass, for example WagTail() then you first need to cast this Animal instance to a Dog class. ((Dog) animals[0]).WagTail()
22nd Oct 2022, 12:33 PM
Tibor Santa
Tibor Santa - avatar
+ 3
Animal, dog classes will have parent, child relationship or have inheritance. So Parent class reference variable can hold child class object also. Here 'Animal dog ' reference variable acts as a polymorphic variable, behaves depending upon the instance assigned. if you assign child instance, then it points to child class also parent class methods because of inheritance. Dog dog = new Dog() ; dog will point only Dog class properties.
22nd Oct 2022, 12:35 PM
Jayakrishna 🇮🇳