Pro Java 9 Games Development Leveraging the JavaFX APIs

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

more predictable and allows developers to safely use that class in programming structures and objectives
where a class of that particular end-usage pattern is suitable for their implementation. As of Java 9 you can
also define private interfaces to be used internally to your app.
The following is an ICar interface, which forces all cars to implement all of the methods that are defined
in this interface. These methods must be implemented and exist even if they’re not utilized, that is, no code
exists inside the curly braces. This also guarantees that the rest of the Java application knows that each Car
object can perform all of these behaviors because implementing an ICar interface defines a public interface
for all Car objects. The way that you would implement the ICar public interface, for those methods that are
currently in your Car class, is as follows:


public interface ICar {
void shiftGears (int newGear);
void accelerateSpeed (int acceleration);
void applyBrake (int brakingFactor);
void turnWheel (String newDirection);
}


To implement an interface, you need to use the Java implements keyword, as follows, and then define
all of the methods exactly as you did before, except that the methods must now be declared using the public
access control modifier in addition to the void return data type. So, you will add the public keyword before
the void keyword, which will allow other Java classes to be able to call or invoke the methods, even if those
classes are in a different package. After all, this is a public interface, and any developer (or more accurately,
any class) should be able to access it. Here is how your Car class should implement this ICar interface by
using the Java implements keyword:


class Car implements ICar {
String name = "Generic";
int speed = 15;
int gear = 1;
int drivetrain = 4;
String direction = "N";
String color = "Red";
String fuel = "Gas ";


public void shiftGears (int newGear) {
gear = newGear;
}
public void accelerateSpeed (int acceleration) {
speed = speed + acceleration;
}
public void applyBrake (int brakingFactor) {
speed = speed - brakingFactor;
}
public void turnWheel (String newDirection) {
direction = newDirection;
}
}


A Java interface cannot use any of the other Java access control modifier keywords, so it cannot be
declared as private (prior to Java 9) or protected. It’s important to note that only those methods declared in
an interface definition will need to be implemented. The data fields that I have at the top of the class definition

Free download pdf