wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Array Reference assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array Reference assignment" Watch "Array Reference assignment" New topic
Author

Array Reference assignment

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
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.


SCJP6
Maciej Drozdzowski
Ranch Hand

Joined: Dec 30, 2009
Posts: 40

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
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40

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

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array Reference assignment
 
Similar Threads
example of dynamic binding
Arrays
Has-A relation
OOP
Object references question