many constructors, structural problem
in
Programming Questions
•
2 years ago
It's not really a problem, but maybe someone has a better way.
I have a class taking in an array.
To be versatile, I want the array to possibly be int[] or long[] or float[].
So I made it with 3 similar constructors, with input of type int[] or long[] or float[].
Now I can not assign this incoming array to a single variable a, since it could be of 3 types.
So I assign it to a_int or a_long or a_float.
Fine.
But then each and every other method to deal with this array has to be tripled, with a dispatching method to call the right one. So I start to feel it would be simpler to just have 3 different methods from the start.
Any comment?
- class graphA {
int arraytype; // (0,1,2 = int,long,float)
int[] a_int;
long[] a_long;
float[] a_float; - graphA(int[] a) {
arraytype=0;
a_int=a;
}
graphA(long[] a) {
arraytype=1;
a_long=a;
}
graphA(float[] a) {
arraytype=2;
a_float=a;
} - void showA() {
switch(arraytype) {
case 0:
showA(a_int);
break;
case 1:
showA(a_long);
break;
case 2:
showA(a_float);
break;
}
}
void showA(int[] a) {
}
void showA(long[] a) {
}
void showA(float[] a) {
}
}
1