简体   繁体   中英

Calling get (array static method) from an array instance

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.

get() is not a method in the array class, (as in a byte[] object). get() is in the Array class. Doing Array.get(testarray, 0) is what you want. Despite that, don't do this, do testarray[0] instead.

Whenever you use a static method, you shouldn't call it from an object, you should use the class instance, so instead of doing

Object o = new Object();
o.staticMethod();

Do:

Object.staticMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM