Results 1 to 3 of 3
- 03-24-2009, 11:25 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 2
- Rep Power
- 0
Array of objects, as an Instance variable
Hullo,
firstly hello to you all..
Secondly, im nedw(ish) to java and prone to doing silly things so i'm probably doing it all wrong BUT
I want to be able to have a class that has as one of its members as an array of objects.
When the class is instanced I want the constructor to assign values to each of the items in the array, using a method of the class in the array.
Like
class MyClass extends otherClass {
public MyClass (x,y,w,h) {
super(x,y)
...etc other constructor stuff
array[0].objectMethod(x,y);
array[1].objectMethod(x+(2*w),y);
... etc for the other array members
}
//Then a Get method for the data
public ObjectType getArray(idx) {
return array[idx];
}
//Declare the class data member like this ??
private ObjectType array[];
}
Thats the general form I want BUT as the "ObjectType" object has not been created I cant call the method to add the members to the array?
Would I do something like..
ObjectType myType = new ObjectType[3];
before calling the methods of the array members? but if so where and how could I call MyClass.getArray(x) ??
I have tried searching/googling but cant find the right words to use in my search, any help would be appreciated...
many thanks
b
- 03-25-2009, 12:19 AM #2
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
Java Code:class MyClass extends otherClass { private ObjectType[] array; public MyClass (int x,int y,int w, int h) { super(x,y) ...etc other constructor stuff array = new ObjectType[3]; array[0] = new ObjectTypeA(x,y,w,h); array[1] = new ObjectTypeB(x,y,w,h); array[2] = new ObjectTypeC(x,y,w,h); } //Then a Get method for the data public ObjectType getArray(int idx) { return array[idx]; } } public class ObjectTypeA extends ObjectType { public ObjectTypeA(int x, int y, int w, int h) { super(...whatever is appropriate here...); ...initialization specific to this type } } ...same thing for ObjectTypeB, ObjectTypeC, etc.
- 03-25-2009, 12:56 AM #3
Member
- Join Date
- Mar 2009
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Naming a class instance with a variable
By pikalex88 in forum New To JavaReplies: 3Last Post: 09-30-2008, 06:27 PM -
Instance Variable In Servlet
By javarishi in forum Java ServletReplies: 3Last Post: 06-14-2008, 08:28 AM -
passing an array into an instance
By lockmac in forum New To JavaReplies: 1Last Post: 08-08-2007, 09:35 AM -
Array with objects
By toby in forum New To JavaReplies: 1Last Post: 07-25-2007, 09:50 AM -
Instance variable
By Jack in forum New To JavaReplies: 2Last Post: 07-04-2007, 04:00 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks