How would I call a Random
from java.util.Random
into a supertype constructor
?
For example
Random rand = new Random();
int randomValue = rand.nextInt(10) + 5;
public Something()
{
super(randomValue);
//Other Things
}
When I try this the compiler says that I "cannot reference randomValue
before supertype constructor
has been called".
Random is not completely random at all. It generates sequences in a perfectly predictable way from the seed. You are completely correct that, since the seed is only 64 bits long, it can only generate 2^64 different sequences.
To generate random number in Python, randint() function is used. This function is defined in random module.
The super()
call must be the first call in the constructor, and any expressions that initialize instance variables will only be evaluated after the super call returns. Therefore super(randomValue)
attempts to pass the value of a variable not yet declared to the super class's constructor.
A possible solution is to make rand
static (it makes sense to have a single random number generator for all instances of your class) and generate the random number in the constructor :
static Random rand = new Random();
public Something()
{
super(rand.nextInt(10) + 5);
//Over Things
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With