firstly hello to you all..

Secondly, im new(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
(for now I only need a fixed number of elements in the array)

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[];
}

That's 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

You can use a for loop to put things into each array index.

You can use a for loop to put things into each array index.

More trouble than its worth as there are only four elements and each has to be computed differently.

I figured out that the line private ObjectType array[]; should read private ObjectType[] array; and then

public MyClass (int x,int y,int w, int h) {
    super(x,y)
    ....
    array = new ObjectType[3];
    ---- etc

but that still gives me an Exception in thread "main" java.lang.NullPointerException error. When i try and call the method for putting data into the class inside the array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.