A (175)

(Tuis.) #1

148 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces


The way that you would implement the ICar public interface for the methods 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);
}


So, the Car class that implements this ICar public interface must implement all of the declared
methods when implementing a Car class using this ICar interface.


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 a public access control modifier, in addition to the void return data type. We will be covering
Java modifiers in a future section of this chapter, after we cover the Java package and the concepts
of APIs.


Here is how a Car class would implement this ICar interface using the Java implements keyword:


class Car implements ICar {
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;
}
}


Notice we added the public keyword before the void keyword, which allows any other Java classes
to be able to call or invoke these methods, even if those classes are in a different package (packages
are discussed in the next section). After all, this is a public interface, and anyone (more accurately,
any class) should be able to access it.

Free download pdf