• 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

Array Reference assignment

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Considering Animal is the superclass of Dog

when I say


An array object is created. Its reference is assigned to a.
This array object can hold three references to Animal.

What is it when I say



Thanks in advance for help.
 
Ranch Hand
Posts: 40
Google Web Toolkit Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
an array object holding three references to Animal - so you can refer to them only by Animal reference, unless you do a cast. inside, it's 3 Dog objects.
a Dog object can also be referenced by an Animal reference, cause Dog-IS-A-Animal
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Anu Kota wrote:
What is it when I say



In Java, arrays have an hierarchy which mirrors the elements that they contain. Meaning a Dog array IS-A Animal array, since a Dog IS-A Animal. This is why you can assign a Dog array to an Animal array reference.

IMO, you should try to avoid this, because a dog array isn't really an animal array. For example, an animal array can hold cat objects too. If you try to assign a Cat element to the array referred to by reference b, the compiler will allow it, in this case (and yes, it will fail at runtime).

Henry
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this 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