简体   繁体   中英

Can you set a multi-object array and call a method from it?

To be exact, I'm curious as to whether an Object[] array is capable of storing and accessing other objects' methods. Here's a little example of what I'm trying to achieve.

//declare an array of *different* objects
private static Object[] function = {new Object1(),
                                    new Object2()}; 
//calls method(getNumber) from Object1()
function[0].getNumber();

Since I already found out that you can stack same objects into an array, I want to figure out if its possible to do so with different methods without using ArrayList. Just curious, so if you think there isn't a way to do this just tell me so, thanks :)

I am not sure what you are asking, but you should cast before calling a method on the plain object. Instead of this:

function[0].getNumber();

You should do something like this:

((MyType) function[0]).getNumber();

If the methods you want to call are the same for all the objects and you control their classes, you should extract the methods to a interface, and let the classes implement it.

This way you could have a CommonInterface[] array...

public CommonInterface { Number getNumber(); }

CommonInterface[] function = { new Object1(), new Object2() };
function[1].getNumber()

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