0

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 :)

  • Its probably easier to just call it directly from the object while declaring them separately, right? – Tan Poh Heng Jul 24 '17 at 08:28
  • You can do it, with a cast: `(Object1)function[0].myObjectMethod();` – Ricardo Jul 24 '17 at 08:29
  • Why does casting work? Is it because the array itself is only declared as an Object[] type array? Sry bout these qns, i legit just started coding less than half a year ago :P – Tan Poh Heng Jul 24 '17 at 08:39
  • Any object array, let's say, MyObject[], is, in it's most basic concept a list of Object with reference to MyObject – Ricardo Jul 24 '17 at 08:45
  • Casting works because this is done at runtime. Not at the compile-time. So, it will case your `Object` into the thing that you are expecting here. – Yuri Jul 24 '17 at 08:54
  • Noted, i guess I'll go read it up if i need more :) – Tan Poh Heng Jul 24 '17 at 09:08

2 Answers2

1

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();
Yuri
  • 1,748
  • 2
  • 23
  • 26
0

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()
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33