I'm a bit confused on the concept of 'Subclass referenced as Superclass' within polymorphism. (referencing here: https://stackify.com/oop-concept-polymorphism/)
Lets say we have the superclass animal and the subclass dog, where dog extends animal. The following work:
- animal testSuper = new animal();
- dog testDog = new dog();
- animal testSuperDog = new dog();
Could anyone explain a bit further on whats happening behind the scenes for #3? When we do 'new dog()', are we creating an object of the dog class but when we do 'animal testSuperDog' we cast it to the superclass animal? Or is it the other way around - 'animal testSuperDog' creates an animal object but we're casting it down to the subclass dog when we do 'new dog()'?
I've tried the 4th permutation to explore and I get a type mismatch error saying that it can't convert from animal to dog. So that's why I'm assuming there's some conversion going on. 4. dog testSubdog = new animal();
If we can dig a bit deeper, since we know #3 works, whats the benefit / use case of this?
- testDog.noise();
- testSuperDog.noise();
Both these would use the 'noise' method from the subclass dog.