I want to create an object that will contain and return multiple objects of various types.
What's the best approach for this? There seems to be several ways out there, so I'm interested to hear different peoples' ideas.
Thanks.
I want to create an object that will contain and return multiple objects of various types.
What's the best approach for this? There seems to be several ways out there, so I'm interested to hear different peoples' ideas.
Thanks.
If you mean to return all of the objects at once, from a single method call, your best bet is to encapsulate all objects into a (possibly inner) class and return an instance of that class.
class Container {
public static class Container {
Type1 obj1;
Type2 obj2;
...
}
private Type1 obj1;
private Type2 obj2;
...
public Container getAllObjects() {
Container container = new Container();
container.obj1 = this.obj1;
...
return container;
}
}
(Technically, you could also return multiple objects within an Object[] array, however I don't recommend this for lack of type safety and open possibilities for making ordering errors.)
If you mean to return the objects one by one, from distinct method calls, good old getters are your friends :-)
class Container {
private Type1 obj1;
private Type2 obj2;
...
public Type1 getObject1() {
return obj1;
}
public Type2 getObject2() {
return obj2;
}
...
}
Well there are 3 ways I can see for you:
-1) use the fact that variable passed are passed by reference. this way you can modify directly the object in your function and not have to worry about return values
-2) you can simple create a array of objects:
Object[] returnTab = new Object[numberToStore];
(this is not very pretty I find)
-3) create a ReturnObjectContainer object
public class container { public ObjectA a; public ObjectB b;
Arraylist list = new list();
... //add whatever you need to store }
What do you mean by "return"? As far as I understand the terms, objects don't return anything, they just are. They can have getters that return an object ofcourse. Could you tell me what several ways you're talking about?
If I understand you correctly you'd just want a class (object) with several private objects (variables) that can be set and gotten trough functions (members).