Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom optional values for constructor

This code is pretty much what I want to do:

import java.util.Random;    

public class TestClass {
  protected int testVarA;
  protected int testVarB;

  public TestClass() {
    Random r = new Random();
    this(r.nextInt(),r.nextInt());
  }

  public TestClass(int testVarA, int testVarB) {
    this.testVarA = startTestVarA;
    this.testVarB = startTestVarB;
  }
}

However, this doesn't compile, since the this() statement has to be at the beggining of the function. I could do something like

this((new Random()).getNextInt(),(new Random()).getNextInt())

But that feels very improper. What is the proper way of doing this?

like image 515
Shelvacu Avatar asked Mar 19 '26 04:03

Shelvacu


1 Answers

I would create your Random object as a static final variable outside of any constructors, so that you can reference it in the first line of your no-arg constructor.

private static final Random r = new Random();

public TestClass() {
  this(r.nextInt(),r.nextInt());
}

This way, you only need one Random object, and it's initialized before the constructor's first line.

like image 183
rgettman Avatar answered Mar 20 '26 17:03

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!