I was explaining to a friend a few days ago the concept or inheritance and containers.
He has very little programming knowledge so it was really just a friendly chat.
During the conversation he came to me with a question that i just couldn’t answer.
“Why cant you just have an array of the top level class, and add anything to it”
I know this is a bad idea having being told so before by someone far smarter but for the life of me i couldn’t remember why.
I mean we do it all the time with inheritance.
Say we have class animal which is parent of cat and dog. If we need a container of both of these we make the array of type animal.
So lets say we didn’t have that inheritance link, couldn’t we just use the base object class and have everything in the one container.
No specific programming language.
Syntactically, there is no problem with this. By declaring an array of a specific type, you are giving implicit information about the contents of that array. You could well declare a contain of
Objectinstances, but it means you lose all the type information of the original class at compile-time.It also means that each time you get an object out of the array at runtime, the only field instances and methods you know exist are the fields/methods of
Object(which arguably is a compile time problem). To use any of the fields and methods of more specific subclasses of the object, you’d have to cast.Alternatively, to find out the specific class at runtime you’d have to use features like reflection which are overkill for the majority of cases.