Corv
Corv

Reputation: 3

Java - Generically handling the creation of subclasses

I have three classes that are quite similar, excepting a single method. Therefore, I chose to put the rest of their functionality into an abstract superclass. When it comes to creating instances of these classes, however, I'm at a loss for how to implement what seems to me like the "obvious" or "elegant" approach. Their constructors are essentially identical, and I need multiple instances of each, so I wanted to do something like the following:

private SubclassA[] subclassA_array, SubclassB[] subclassB_array, SubclassC[] subclassC_array;
subclassA_array = new SubclassA[getNumInstancesOfClassANeeded()]
subclassB_array = new SubclassA[getNumInstancesOfClassBNeeded()]
subclassC_array = new SubclassA[getNumInstancesOfClassCNeeded()]

// might have my syntax wrong here; array of the three subclass arrays
private Superclass[][] superArray = new Superclass[][3];
superArray[0] = subclassA_array;
superArray[1] = subclassA_array;
superArray[2] = subclassA_array;
for ( Superclass[] array: superArray )
    for(int i = 0; i< array.length; i++)
      //  array[i] = new..... what goes here?
    }
}

How would I find the appropriate class to construct in that innermost loop? Is this actually a really oddball way of approaching the problem; have I missed something more obvious? Should I just say "to hell with it!" and just have three separate loops?

Upvotes: 0

Views: 87

Answers (3)

Stephen C
Stephen C

Reputation: 718768

Should I just say "to hell with it!" and just have three separate loops?

IMO, yes.


You could do the following:

  1. Use array.getClass() to get the class of the array,
  2. Use getConmponentType() to get the array's base type
  3. Use newInstance() to create an instance
  4. Assign the instance reference to the array.

... but this results in fragile code and is like using a sledge-hammer to crack a walnut.

Upvotes: 1

SJuan76
SJuan76

Reputation: 24780

You can create an static method

public static subclassA[] getNewInstances(int numberOfInstances);

static methods can be accessed without the need to create a new instance SubclassA.getNewInstances(3).

In your definition of the matrix, you need to define first the first dimension (so it becomes new Superclass[3][]

Upvotes: 0

michael667
michael667

Reputation: 3260

You could work with reflection in your inner loop, something like array.getClass().getComponentType().newInstance(), but I think there might be better solutions to the overall problem (To answer that, I'd need more information about what you want to code)

Upvotes: 0

Related Questions