• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Assigning an Array of One Type to its Supertype

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Tomorrow is the first day of the new metric calendar. Comfort me tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic