Constructor Parameters
Estimated time to read: 1 minute
To create objects with dynamic, individual states, we’ll use a combination of the constructor method and instance fields.
In order to assign a value to an instance variable, we need to alter our constructor method to include parameters so that it can access the data we want to assign to an instance.
We’ve already seen a parameter in the main() method: String[] args, but this is the first time we’re using the parameter value within a method body.
The Car constructor now has a parameter: String carColor:
public class Car {
String color;
// constructor method with a parameter
public Car(String carColor) {
// parameter value assigned to the field
color = carColor;
}
public static void main(String[] args) {
// program tasks
}
}
When a String value gets passed into Car(), it is assigned to the parameter carColor. Then, inside the constructor, carColor will be assigned as the value to the instance variable color.
Our method also has a signature which defines the name and parameters of the method. In the above example, the signature is Car(String carColor).
There are two types of parameters: formal and actual. A formal parameter specifies the type and name of data that can be passed into a method. In our example above, String carColor is a formal parameter; carColor will represent whatever String value is passed into the constructor. We’ll learn about actual parameters in the next exercise.