New to Java, and OOP in general.
I'm doing an online Lynda course, and in the course there's an example of using Array.get
to extract the 2nd item from an array:
String[] myFavoriteCandyBars = {"Twix", "Hershey's", "Crunch"};
System.out.println(Array.get(myFavoriteCandyBars, 2));
And the instructor explained that get is a static method from the "Array" class.
But when I tried defining:
`Array[] testarray = new Array[10];`
And using:
`testarray.get(testarray[10]);`
I get an error:
cannot resolve method 'get(java.lang.reflect.Array)'
But I don't understand why - the testarray
is an object of class Array, and class Array has a method "get", so although it's bad practice, why can't I do it?
The Array
class is an internal Java class containing only public static methods, and its intended use is to not be be directly instantiated. The following code:
testarray.get(testarray[10]);
fails because testarray
is of type Array[]
, not Array
, and therefore does not have the static method get()
available. Hypothetically speaking, if you could call Array#get
on an instance, it should work, but as mentioned above, Array
cannot be instantiated.
A more typical way to use Array
would be something like:
String[] testarray = new String[10];
testarray[1] = "Snickers";
System.out.println(Array.get(testarray, 1));
That is, create an array of the desired type, and then use Array#get
to access whichever element you want.