• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assigning an Array of One Type to its Supertype  RSS feed

 
Russ Russell
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am assigning and array of type Dog to an array of Animals (implicit upcast - Dog extends Animal), and I am getting different results than I expect. Would someone please explain why the array of Animals doesn't receive the Dog values (code below)?

Thank you in advance,
-Russ
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a[x] is defined to be a reference to an Animal. The fact that it happens to point to a Dog object at runtime doesn't change that. Member variables are not runtime polymorphic. Only non-private, non-static, non-final methods are. So, for instance, you could replace the name variable with a getName() method, and have Animal return "Animal" and Dog override it to return "Dog".

In general, non-private member variables are a bad idea, as is naming a member variable in a subclass the same as a variable that's accessible in an ancestor class.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!