August 2017
Intermediate to advanced
440 pages
10h
English
In Java, arrays are co-variant. By default, we can pass an array of String[] even if an array of Object[] is expected:
public class Computer { public Computer() { String[] stringArray = new String[]{"a", "b", "c"}; printArray(stringArray); //Pass instance of String[] } void printArray(Object[] array) { //Define parameter of type Object[] System.out.print(array); } }
This behavior was important in early versions of Java, because it allowed us to use different types of array as arguments:
// Java static void print(Object[] array) { for (int i = 0; i <= array.length - 1; i++) System.out.print(array[i] + " "); System.out.println(); } // Usage String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; print(fruits); ...Read now
Unlock full access