I have a class with a method that generates random data to fill arrays with. The class had the data member private final Random rnd
that is initialized in the constructor with new Random();
. This is used in the method for generating data for arrays.
For example
package test;
import java.util.Random;
public class WorkWithArrays {
WorkWithArrays(Object[] arr) {
rand = new Random();
fillArrays(arr);
}
/*fills arrays with random data;
since this method is called from constructor
must be declared final*/
public final void fillArrays(Object[] arr) {
//code goes here
}
/*some other methods and data members*/
final private Random rand;
}
I am writing a new class which I also need to fill arrays with random values. Is there a way I could not have to rewrite the same method? I could extend
the class or I could make the method static. Since I only need fillArrays()
making it static
seems like the better option over extend
ing.
So let's make it static.
public static final void fillArrays(Object[] arr) {
//code goes here
}
Now fillArrays()
uses rand
which is a problem because rand
isn't static. So why not make it static? Now in WorkWithArrays
we no longer initialize rand
in the constructor but have it final static private Random rand = new Random();
as a data member. Is this right? It seems like bad practice to initialize things outside of the constructor.
Now I can do
package test;
MyNewClass {
someMethod() {
int[] x = new int[25];
WorkWithArrays.fillArrays(x);
}
}