I know what a static array is and how to use it in Java, but my Prof assigned us a program and for one of the many classes we had to create, he asked us to ‘use a static array’ in such a way that multiple objects will store their data there.
For instance, if the objects were car garages, then each garage instance would store in a 100×3 static array their data:
1, honda, four-door
3, toyota, two-door
1, bicycle, -1
1, ford, pickup
2, ford, fiesta
3, chevy, two-door
3, bicycle, -1
The -1 indicates the end of each garage.
That’s a lousy example, but you get the idea.
So, I am thinking that what he wants is kind of like this:
In the demo class (which is the main), I will declare an instance of a class I made with the static array in it:
PublicAccessArray p1 = new PublicAccessArray();
Then that class starts off like:
public class PublicAccessArray {
public static int[][] accessArray;
public static void PublicAccessArray()
{
accessArray = new int[100][3];
...
And then my class that will create the objects to use the static array will look like:
public class ClassThatUsesTheStaticArray {
public void ClassThatUsesTheStaticArray (PublicAccessArray array1)
{...
So then back in the demo/main class I would instantiate those objects with:
ClassThatUsesTheStaticArray c1= new ClassThatUsesTheStaticArray (p1);
I think that’s what he means, and I know that the static array should look like the example I gave (though it uses numbers as data/elements).
I know he wants us to instantiate the ClassThatUsesTheStaticArray objects from the demo/main class and the only way I can see to do that would be to pass the p1 array to it.
Does what I am doing seem to be the right way? I often an easier time doing the actual coding than figure out what my Prof. is actually asking us to do so I was wondering if that sounds like a way to ‘use a static array’.
I do not think that you are on a right way.
First you cannot store “honda” or “toyota” in int array. So you need String array. The first column looks like index, so you do not have to store it in your array at all.
Second, the example is not OO enough. I’d suggest you the following.
Create class Vehicle:
Then create classes Car and Bicycle that extend Vehicle. These classes can contain other data:
Now create class Garage:
This is the time to create static array of garages:
You can populate it using static initializer (I assume here existence of convenient constructors I did not mention in my explanation):
I believe your Prof will be satisfied. Good luck!