Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using randoms and super

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".

like image 667
Dan Avatar asked Jun 28 '15 09:06

Dan


People also ask

Is random in Java really random?

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.

How do I get a random number in Python?

To generate random number in Python, randint() function is used. This function is defined in random module.


1 Answers

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
}
like image 119
Eran Avatar answered Sep 28 '22 05:09

Eran