Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1

Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples


drivetrain = 4;
direction = carDirection;
color = carColor;
fuel = "Gas";
}
}


It is important to note here that constructor methods can be declared without using the public
keyword, as long as the classes containing nonpublic constructors do not need to be instantiated from
beyond their packages. If you wanted to code one constructor invoking another constructor using this(), you
could do this as well. For example, Car() might execute the constructor method call this(“myCar”, 10, 1, 4,
“N”, “red”);, and this would be legal Java code.
To use the overloaded Car() class constructor and the Java new keyword to create a new Car object, you
would use like the following Java code:


Car carOne = new Car(); // Creates a Car object using default values
Car carTwo = new Car("Herbie", 25, "W", "Blue"); // Creates a customized Car object


The syntax for constructing an object is similar to declaring a variable but also uses the Java new
keyword:


•    Define the object type Car.

•    Give a name to the Car object (carOne, carTwo, etc.) that you can reference in the
class Java code.

•    Use the default Car() constructor method to create your generic or default Car
object, or...

•    Use an overloaded Car(name, speed, direction, color) constructor with different
value parameters.

Invoking the Car object methods using these Car objects requires the use of something called dot
notation, which is used to chain or reference Java constructs to each other. Once the Java object has been
declared, named, and instantiated, you can then call methods “off of it.” This would be done, for example,
using the following Java code:


objectName.methodName(parameter list variable);


So, to shift to third gear, for the Car object named carOne, you would use this Java programming
statement:


carOne.shiftGears(3);


This “calls” or “invokes” the .shiftGears() method “off of ” the carOne Car Object and “passes over” the
gear parameter, which contains an integer value of 3, which is then placed into the newGear variable, which
is utilized by the .shiftGears() method internal code to change a gear attribute of that Car object instance,
setting a new value of 3.
Java dot notation “connects” the Java method call to the Java object instance, which then invokes, or
“calls,” that method off of (or from or for) that Java object instance. If you think about it, how Java works is
logical and cool.

Free download pdf