Andrea said:
so if I have the following methods:
void foo( Base[] bases )
void bar( Object[] objects )
I can call:
foo( derivedArray )
bar( derivedArray )
bar( baseArray )
Yes. But to be certain I'm not giving you false information (and because
I've got too much time on my hands), I wrote and compiled the following
code:
/* BEGIN CODE EXAMPLE */
class Base {}
class Derived extends Base {}
public class TestArrayPolymorphism {
public static void main(String [] args) {
Base [] baseArray = new Base[4];
Derived [] derivedArray = new Derived[4];
foo(derivedArray);
bar(derivedArray);
bar(baseArray);
System.out.println("Finished.");
}
public static void foo(Base [] bArray) {
System.out.println("foo called with argument " + bArray);
}
public static void bar(Object [] oArray) {
System.out.println("bar called with argument " + oArray);
}
}
/* END CODE EXAMPLE */
The code compiled without error, and running it gives the following output.
foo called with argument [LDerived;@1add2dd
bar called with argument [LDerived;@1add2dd
bar called with argument [LBase;@eee36c
Finished.
However, (and this is what I was thinking of a few posts ago when I was
confused) you CANNOT assume the same is true for primitive arrays. For
example, you cannot assign a byte array to a reference variable declared
to be an int[] array, even though you are permitted to store a byte
value in an int variable. (You can still store a byte into an *element*
of an int array, e.g. intArray[0] = byteValue.)
Is there a place where I can find it? Is it in the language
specification somewhere?
To be honest, I'm not sure. I only know because I taught myself with a
book that trains you for the SCJP exam.
Let me see... a quick search turned up the Java Language Specification
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html#27805
The Sun Java Tutorials don't seem to mention this in their array
section, so the Java Language Specification is probably your best resource.