Skip to main content

Section 4.3 Worked Example: Create Instance of Random

Subgoals for using objects (creating instances).

  1. Declare variable of appropriate class datatype.
  2. Assign to variable: keyword new, followed by class name, followed by ().
  3. Determine whether parameter(s) are appropriate (API)
    1. Number of parameters
    2. Data types of the parameters

Subsection 4.3.1

You can watch this video or read through the content below it.
The following Java code declares and instantiates a variable that will be used to generate random values.

Subsection 4.3.2 SG1: Declare variable of appropriate class datatype.

In the code block below, the variable name randGen was selected to better describe this object’s purpose as a random number generator.
Random randGen;

Subsection 4.3.3 SG2: Assign to variable:  keyword new, followed by class name, followed by ().

randGen = new Random();

Subsection 4.3.4 SG3: Determine whether parameter(s) are appropriate (API)

The figure below shows the Java documentation, so we can determine what parameter(s) we need. If we wanted a specific seed value, we could use that, but for most purposes, allowing the constructor to select its own seed is ok.
Figure 4.3.1.
So the final code looks like this:
Random randGen;
randGen = new Random();
Notice in the ActiveCode box below, we have added the appropriate import statement for using the Random class.

Practice Pages.

You have attempted of activities on this page.