142 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces
A constructor method is used to construct an object and to configure it, so the first thing that we
will want to do is to make our variable declarations undefined, by removing the equal sign and
initial data values, as is shown in the following code. A Car( ) constructor method will set data
values, as part of the construction and configuration of the Car object, and thus the Java code for
the Car( ) constructor method could be written as follows, where we specify the car name in the
constructor’s parameters:
class Car {
String name;
int speed;
int gear;
int drivetrain;
String direction;
String color;
String fuel;
public Car (String carName) {
name = carName;
speed = 15;
gear = 1;
drivetrain = 4;
direction = "N";
color = "Red";
fuel = "Gas";
}
}
A Java constructor method differs from a regular Java method in a number of distinct ways. First of
all, it does not use any of the data return types, such as void and int, because it is used to create a
Java object, rather than to perform a function. It does not return nothing (void keyword) or a number
(int or float keywords), but rather returns an object! Indeed, that’s why it’s called a constructor in the
first place; because its function is solely to construct or create the new Java object; in this particular
case, that would be a Car object.
Note that every class that needs to create a Java object will feature a constructor with the same
name as the class itself, so a constructor is the one method type whose name can (and will, always)
start with a capital letter.
Another difference between a constructor and a method is that constructors must have a public
access control modifier, and cannot use any non-access-control modifiers, so be sure not to declare
your constructor as: static, final, abstract, or synchronized. We will be covering modifiers a bit
later on in this chapter, so stay tuned!
In case you may be wondering how you would modify the previous Car( ) constructor method
example if you wanted to not only name the new Car object using the constructor method, but also
wanted to define its speed, direction, and color using that same Car( ) constructor method call,