Concepts / Constructors and Object Creation in Java

Constructors and Object Creation in Java

Date, Random, and Color are standard Java classes in java.util and java.awt, and each must be imported before use.

  • Programming

Same Line, Different Output

Java's standard library contains many classes that solve common problems so that you do not have to write the solutions yourself. This article looks at three of them: Date, which represents times and dates, Random, which produces random numbers, and Color, which represents colors for drawing. Each of them is created with a constructor, and the act of creating one is the starting point for everything that follows.

What do you think happens?

If you write a program that creates a Date object with no parameters and prints it, and you run it on two different days, will the printed output be the same both times?

  • Yes, the printed date is always the same because it is written in the source code

  • No, the printed value depends on the moment the object was created

Reveal answer
Answer:

No, the printed value depends on the moment the object was created

A Date created with no parameters represents the current date and time. The value comes from the time the object was created, and the program does not store a fixed date in its source code, so the output changes between runs.

What a Constructor Call Produces

A constructor is the part of a class that runs when you write new followed by the class name and parentheses. Writing new Date() creates a Date object, and writing new Color(255, 0, 0, 255) creates a Color object. The value you create is connected to a variable, which holds a reference to the object. The variable does not hold the object's contents itself; it points to the object that the constructor produced.

nowvariable holding areferenceDate objectcurrent date and timerefers to
After new Date() runs, how does the variable relate to the object the constructor created?

Follow the diagram from the variable. The arrow shows that the variable refers to the object, and the object is the thing the constructor built. Keeping this picture in mind makes the later examples easier to read, because every constructor call in this article follows the same pattern: a new object is built, and a reference to it is stored.

Date: A Snapshot of the Moment

The Date class belongs to the package java.util. Before the class can be used, the program must import it by naming that package. The example below creates a Date with no parameters, which captures the current date and time, and then prints it. The import line tells the compiler where Date lives.

java
Output
The printed line shows the date and time at the moment the object was created. The exact text differs each time the program runs.
Notes on the code
  • import java.util.Date; names the package that contains the Date class
  • new Date() calls the no-parameter constructor, which records the current date and time
  • System.out.println(now) prints the value stored in the object

Random Numbers in a Chosen Range

The Random class is a source of random numbers. An object of type Random produces pseudorandom numbers. The word pseudorandom matters: the numbers come from a deterministic procedure that looks random, not from a physical process. The standard function Math.random() uses an object of this kind behind the scenes, so Random is the class that does the actual work whenever Java generates random values. A Random object can produce random integers and random real numbers, and it can also produce Gaussian distributed values, which follow a bell-shaped distribution. This article focuses on integers.

The method nextInt(N) produces integers from 0 up to N minus 1. That means the raw result of nextInt(6) can be 0, 1, 2, 3, 4, or 5, but never 6. To shift the range so that it starts at 1, you add 1 to the result. The expression nextInt(N) + 1 is the standard way to produce integers from 1 through N.

0rolls 11rolls 22rolls 33rolls 44rolls 55rolls 6
For nextInt(6) + 1, which raw values are possible and what face does each one produce?
Formula, step by step
  1. 1
    nextInt(N) returns an integer from 0 up to N minus 1
  2. 2
    Adding 1 moves every possible result up by one
  3. 3
    The final range is 1 through N, inclusive

Simulating a Six-Sided Die

Worked example

One roll of a six-sided die

Write an expression that simulates one roll of a six-sided die, and state which values it can produce.

  1. 1
    Create a Random object

    new Random() constructs the object that will produce the numbers. It must be imported from java.util first.

  2. 2
    Choose the raw range

    nextInt(6) produces integers from 0 to 5, which is six possible values, one for each face of the die when shifted.

  3. 3
    Shift the range

    Adding 1 gives nextInt(6) + 1, which moves the possible results from 0 to 5 up to 1 to 6.

  4. 4
    Check the bounds

    The smallest possible result is 0 + 1 = 1 and the largest is 5 + 1 = 6, so the range is exactly the faces of a die.

Result

The expression rand.nextInt(6) + 1 can produce any integer from 1 through 6, and no other value.

java
Output
A single integer from 1 to 6. Each run may print a different value.
Notes on the code
  • import java.util.Random; names the package that contains the Random class
  • new Random() constructs the random number source
  • nextInt(6) + 1 produces a value from 1 through 6

Color and Its Four Channels

The Color class is in the package java.awt and represents a color that can be used for drawing. You have probably already used constants such as Color.RED. Those constants are final static member variables of the Color class, and their values are themselves objects of type Color. You can also create new Color objects with a constructor that takes four int parameters: the red, green, and blue components, followed by the alpha component.

Each of the first three parameters sets how much red, green, or blue the color contains. A value of 0 means none of that component, and 255 means the maximum possible amount. The fourth parameter, alpha, controls transparency. A larger alpha value produces a more opaque color, so the background shows through less. The class also has other constructors, including one without the alpha parameter that produces fully opaque colors.

java
Output
255
Notes on the code
  • import java.awt.Color; names the package that contains the Color class
  • The first argument, 255, sets the red component to its maximum
  • The second and third arguments are 0, so green and blue contain none
  • The fourth argument, 255, sets alpha to fully opaque
  • getRed() reads back the red component

Why a Color Cannot Change

A Color object has only a few instance methods that you are likely to use, such as getRed(), which reads one of the color components. There are no setter methods for changing the components. The reason is that a Color is immutable: all of its instance variables are final, so they cannot be changed after the object is created. Once a Color has been built with its four values, those values stay fixed for the life of that object.

This design changes how you work with colors. If you want a different color, you do not modify the existing object. Instead, you create a new Color object with the values you want and point the variable at it. The code below shows this pattern. The first line creates a red Color and the second line gives the variable a new blue Color.

Before
Color c = new Color(255, 0, 0, 255);

The variable c refers to a red Color object.

After
c = new Color(0, 0, 255, 255);

The variable c refers to a new blue Color object. The red object was not modified; it simply is no longer the value of c.

cpoints to red Colorred ColorColor(255, 0, 0, 255)cpoints to blue Colorblue ColorColor(0, 0, 255, 255)red ColorColor(255, 0, 0, 255)refers torefers to
When c is given a new blue color, what stays the same, what becomes a new object, and what does c point to afterward?

Immutable Objects and Where They Appear

Definition

An immutable object is an object whose state cannot be changed after it is created. In Java, a class is immutable when its instance variables are final, so they are assigned once and never reassigned. The Color class is the example used in this article, and the source also notes that String is another immutable class.

Immutability does not mean that a variable can never be reassigned. The variable c in the previous example was reassigned to a new Color. What cannot happen is changing the internal values of the object that c referred to. The distinction between the variable and the object it refers to is the key to understanding immutability.

The source states that later chapters will show how to write some immutable classes of your own. For now, the important skill is recognizing immutable classes when you meet them and expecting that changes will appear as new objects rather than as edits to existing ones.

Mistakes Beginners Make

  • Common mistake

    Using Date, Random, or Color without importing their package

    What it looks like

    Date now = new Date(); with no import line above it

    Why it fails

    Each of these classes lives in a package (java.util or java.awt), and the source states that each must be imported before use.

    Do this instead

    Add import java.util.Date; (or the matching import for Random or Color) at the top of the file.

  • Common mistake

    Assuming nextInt(6) produces values from 1 to 6

    What it looks like
    int roll = rand.nextInt(6);  and expecting roll to be 6 sometimes
    Why it fails

    nextInt(N) produces integers from 0 to N minus 1, so 6 is never returned.

    Do this instead

    Use rand.nextInt(6) + 1 to get values from 1 through 6.

  • Common mistake

    Expecting a Date to show the time when the output is printed

    What it looks like

    Creating a Date, waiting, and assuming the printed value is updated

    Why it fails

    The time is captured when the Date is constructed, so the printed value reflects the creation moment.

    Do this instead

    Create a new Date object at the moment you need a fresh value.

  • Common mistake

    Looking for a setter to change a Color

    What it looks like
    red.setRed(0);
    Why it fails

    A Color has no setter methods because its instance variables are final and cannot be changed after creation.

    Do this instead

    Create a new Color with the desired values and assign it to the variable.

  • Common mistake

    Treating Random output as a true physical source of randomness, when it is a pseudorandom procedure

Practice Your Object Creation

EASY

Write a Java expression using a Random object named rand that produces an integer from 1 through 10 inclusive. State the smallest and largest value it can return.

Hints
  • nextInt(N) produces integers from 0 up to N minus 1.
  • Choose N so that the raw range covers 10 possible values, then add 1 to shift it.
MEDIUM

Create a Color object that is pure blue and fully opaque, then explain in one sentence what you would do if you later wanted a green color instead. Your answer should not modify the blue object.

Hints
  • The four constructor arguments are red, green, blue, and alpha, in that order.
  • Remember that Color objects are immutable, so the replacement is a new object.

Key Takeaways

  • A constructor call such as new Date(), new Random(), or new Color(...) creates an object, and a variable holds a reference to it.
  • A Date created with no parameters captures the current date and time at the moment of creation, so its printed output changes between runs.
  • nextInt(N) produces integers from 0 to N minus 1, and nextInt(N) + 1 shifts that range to 1 through N.
  • A Color takes red, green, blue, and alpha values from 0 to 255, and it is immutable because its instance variables are final, so changing a color means creating a new Color object.
  • Date, Random, and Color belong to java.util and java.awt and must be imported before use.