I have seen other answers to similar questions but all of them rely on the fact that the language is defined to be like this. Following is what I am seeking an explanation to:
In an inheritance hierarchy, the parent types can hold child objects implicitly (why?), however for the child references to hold a parent object, explicit downcast is necessary (why?).
Please cite some example that explains why not doing this will fail, I mean using Animal, Dog type etc. If this question is already answered and I have missed it, citing that also will be helpful.
For example:
class Animal{
public void eat(){};
}
class Dog extends Animal{
public void bark(){};
}
class App{
Animal an = new Dog(); //1. why can animal store a dog but not a dog store an animal
Dog dog = (Dog) new Animal(); //2. Dog has the behavior of an Animal so why explicit downcast
}
I just want to know how this lines make sense, other than just knowing they are language semantics. Better if your answer looks like that as a granny explaining this to her grandchild.
Edit:
I just was wondering that Dog
inherits Animal
and has all the behavior. Hence number 2 above should have been allowed without explicit downcasting.
Or, that (I think I got it now) when I ask a Dog
to store an Animal
there are possibilities that I actually get a Cow
or a Horse
, because Animal
being parent can hold any of its subtypes. If that's the case then why has Java allowed Animal
to hold subtypes since there might be behavior typical to subtypes like a Dog
will bark()
, for that again compiler has to check and report. I know the rules just trying to reason out in the simplest of sense.