Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples

the first thing that you’ll want to do is to make the variable declarations undefined, removing the equal sign
and initial data values, as shown here:


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";
}
}


Instead, the Car() constructor method itself will set data values as part of the construction and
configuration of the Car object. As you can see, I added a String name variable to hold the Car object’s name
(carName parameter).
A Java constructor method will differ from a regular Java method in a number of distinct ways. First
of all, it will 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 of type java.lang.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 should always) start with a capital letter. As I mentioned, if you do not
code a constructor, the Java compiler will create one for you!
Another difference between constructor methods and any other method is that constructors need
to utilize the public access control modifier and can’t use any non-access-control modifiers. If you’re
wondering how to modify the previous Car() constructor method, say if you wanted to not only name your
Car object using the constructor method but also define its speed, direction, and color using an overloaded
Car() constructor method call, you might accomplish this more advanced objective by creating a longer
parameter list for your constructor by using this following code:


class Car {
String name;
int speed;
int gear;
int drivetrain;
String direction;
String color;
String fuel;
public Car (String carName, int carSpeed, String carDirection, String carColor) {
name = carName;
speed = carSpeed;
gear = 1;

Free download pdf