This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating arrays of objects  RSS feed

 
Tomas L�fstrand
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a class named Dog which extends a class named Animal, why exactly is the following not legal:

Dog[] niceAnimals = new Animal[2]; // Why not?

The following is OK:

Animal[] niceAnimals = new Dog[2]; // OK

And certainly this:

Animal[] niceAnimals = new Animal[2]; // For "polymorphic" reasons
niceAnimals[0] = new Dog();
niceAnimals[1] = new Animal();

Thank you advance!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because a bird is an animal, but it is not a dog.

in other words, your array niceAnimals of Dogs can ONLY hold Dogs (or sub-classes of Dogs). but your array of Animals MIGHT have a bird, a fish, or a cockroach in it. they are all animals, so they all go nicely into it, but they are not Dogs.
[ January 24, 2006: Message edited by: fred rosenberger ]
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To extend the metaphor of this post a little further, just because a Dog is an Animal, this does not mean every animal may be a dog. I could be a (ewww) Cat or a Hamster.
Therefore:

Part of the reason for subclassing as I see it is to offer additional specialized functionality that the superclass can not, or should not reasonably offer for a general case. For instance if you have a method That would be inapproriate for Animal class (all animals dont lay eggs), but totally appropriate for Snake class. I hope I heven't confused the issue more by my convoluted answer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!