Sub topic 5
Initializing objects with constructors
A new object needs a starting state. A bank account might start with a balance, or a plant might start with a name and a height. In Java, a constructor sets up that starting state when you create the object.
A constructor is a special part of a class that runs as part of creating an object. A class is a definition for objects, and an object is one item created from that definition. Each object has its own instance fields, or variables that hold its state.
In this chapter, you will write constructors, pass them values, and see what happens when a class has no constructor of its own.
A constructor for a plant
Here is a complete program. Save it in a file named PlantDemo.java.
class Plant {
String name;
int heightCm;
Plant(String name, int heightCm) {
this.name = name;
this.heightCm = heightCm;
}
void grow(int amountCm) {
heightCm = heightCm + amountCm;
}
}
public class PlantDemo {
public static void main(String[] args) {
Plant basil = new Plant("Basil", 12);
Plant mint = new Plant("Mint", 8);
System.out.println(basil.name + ": " + basil.heightCm + " cm");
System.out.println(mint.name + ": " + mint.heightCm + " cm");
basil.grow(3);
System.out.println(basil.name + " after growing: " + basil.heightCm + " cm");
}
}To run it, you need a Java Development Kit, or JDK, installed. In a terminal, go to the folder containing the file and run:
javac PlantDemo.java
java PlantDemoThe output is:
Basil: 12 cm
Mint: 8 cm
Basil after growing: 15 cmThe Plant constructor gives each plant its name and starting height. The grow method then changes the height of the basil plant. The mint plant keeps its own height.
Read the constructor
Look at the constructor on its own:
class Plant {
String name;
int heightCm;
Plant(String name, int heightCm) {
this.name = name;
this.heightCm = heightCm;
}
public static void main(String[] args) {
Plant plant = new Plant("Basil", 12);
System.out.println(plant.name + ": " + plant.heightCm + " cm");
}
}This program can be saved as Plant.java and run on its own.
A constructor has these parts:
- Its name is the same as the class name:
Plant. - Its parentheses contain its parameters. A parameter is a variable that receives a value when the constructor is called.
- Its body is the code between
{and}. This body sets the fields.
The parameters are String name and int heightCm. Their types say what kinds of values the constructor needs: text for the name and an integer for the height.
A constructor does not declare a return type. That is one way it differs from a method. For example, void Plant(...) would declare a method named Plant, not a constructor.
Pass values when creating an object
Consider this line from the first program:
Plant basil = new Plant("Basil", 12);
The word new creates a Plant object and calls its constructor. The values inside the parentheses are arguments. An argument is a value supplied to a constructor or method.
Java matches the arguments to the parameters by position:
| Argument | Parameter | Value received |
|---|---|---|
| `"Basil"` | `name` | `"Basil"` |
| `12` | `heightCm` | `12` |
After the constructor finishes, the new expression produces a reference to the new object. A reference is a value that lets you access an object. The variable basil receives that reference.
The next call, new Plant("Mint", 8), creates a separate object. It runs the constructor again with different arguments. Each call gives its new object a starting name and height.
The number, order, and types of arguments must match the constructor. For this Plant class, a call with only a name, or with the height before the name, will not compile.
Use `this` to name the object's fields
Inside the constructor, the parameter name and the field name have the same name:
this.name = name;
The two sides mean different things:
this.nameis the field of the object being created.nameis the parameter holding the argument.=assigns the parameter's value to the field.
The same pattern sets the height with this.heightCm = heightCm.
The word this refers to the current object. In this constructor, it means the new plant whose fields are being set.
If you wrote name = name; instead, both uses of name would refer to the parameter. The field would not receive the value. Using this.name makes it clear that the field is on the left side.
You can also give parameters different names from fields. For example, a parameter named plantName could be assigned with name = plantName;. The this.name style is useful when you want the field and parameter to share a name.
What happens during creation
For the Plant example, you can think of creation in these stages:
Before the constructor body runs, Java gives the object's fields initial values. The constructor body can then replace those values. Once the constructor finishes, the surrounding expression can use the reference to the object.
The constructor does not declare a return type or return the reference as a method would. The new Plant(...) expression produces the reference.
Constructors with no parameters
A constructor can have empty parentheses. It then takes no arguments.
Save this program as ClockDemo.java:
class Clock {
int hour;
Clock() {
hour = 9;
}
}
public class ClockDemo {
public static void main(String[] args) {
Clock clock = new Clock();
System.out.println(clock.hour);
}
}The output is 9. The call new Clock() creates a clock and runs Clock(). The constructor sets hour to 9.
This constructor is useful when every new object should begin with the same value, so the caller does not need to provide it.
When you do not write a constructor
If a class declares no constructors, Java supplies a default constructor: a constructor with no parameters. You can use it to create an object with empty parentheses.
Save this program as LampDemo.java:
class Lamp {
boolean on;
int brightness = 50;
String label;
}
public class LampDemo {
public static void main(String[] args) {
Lamp lamp = new Lamp();
System.out.println(lamp.on);
System.out.println(lamp.brightness);
System.out.println(lamp.label);
}
}The output is:
false
50
nullThe Lamp class has no constructor in its source code, so Java supplies a default constructor. Its fields still get starting values:
| Field | Starting value | Reason |
|---|---|---|
| `on` | `false` | Java's default value for a `boolean` field |
| `brightness` | `50` | The value assigned where the field is declared |
| `label` | `null` | Java's default value for a reference field |
The value null means the reference does not refer to an object. Other field types have defaults too: for example, an int field without an assigned value starts at 0.
A value written at the field declaration, such as brightness = 50, is called a field initializer. It runs before the body of that class's constructor.
These defaults apply to fields. Do not rely on them for local variables inside a method or constructor; you must assign those variables before reading them.
A common constructor mistake
Java supplies a default constructor only when the class declares no constructors. It does not add one just because you want to call it.
The earlier Plant class declares Plant(String name, int heightCm). As a result, a call to new Plant() would fail to compile: that class does not have a constructor with no parameters.
Similarly, a constructor must have exactly the class name and no declared return type. If you accidentally add void before Plant, Java treats it as a method. That method will not set up an object when you call new Plant(...).
When a constructor call fails, check these points:
- Does the constructor name match the class name exactly, including capital letters?
- Does the constructor have no declared return type?
- Does the call provide the right number of arguments, in the right order and with suitable types?
- If the parameters and fields share names, does the constructor assign values to the fields using
this?
Check your understanding
Exercise
A class has a constructor Book(String title). What value does title receive in new Book("Java Basics")?
Show answer
It receives the string "Java Basics", which the constructor can use to set the new book's field.
Exercise
A class declares only Plant(String name, int heightCm). Will new Plant() compile?
Show answer
No. The declared constructor needs two arguments, and Java does not supply a default constructor when the class declares a constructor.
Exercise
Inside a constructor, what is the difference between this.name = name; and name = name; when name is also a parameter?
Show answer
The first assigns the parameter's value to the object's field. The second assigns the parameter to itself and leaves the field unchanged.