Defining Interfaces
How to write a Java interface and implement more than one in a class with the `implements` keyword.
Journeyman · Java · OOP · Updated
Interfaces are created like abstract classes are, with a few minor differences.
- You don't write the
abstractkeyword: a method in an interface with no body is abstract automatically - You don't declare a method's visibility: methods in an interface are public automatically
Following are the definitions of the interfaces described earlier. Notice that there are no method bodies for any of the methods.
public interface Drivable
{
void turnOn();
}
public interface BladeController
{
int getBladeSpeed();
void setBladeSpeed(int speed);
void turnOn();
}
To implement an interface, we use the implements keyword, and then use a comma separated list of all interfaces we want to use.
We must write method implementations for all methods defined by the interfaces.
This class implements both interfaces:
public class RidingMower implements Drivable, BladeController
{
private String make;
private String model;
private int bladeSpeed;
public RidingMower(String make, String model, int bladeSpeed)
{
this.make = make;
this.model = model;
this.bladeSpeed = bladeSpeed;
}
// this overrides both Drivable AND BladeController
@Override
public void turnOn()
{
System.out.println(make + " has been turned on");
}
@Override
public int getBladeSpeed()
{
return bladeSpeed;
}
@Override
public void setBladeSpeed(int speed)
{
bladeSpeed = speed;
}
}
Do it: give the mower a fuel tank
The shop's riding mower needs a fuel gauge, and its tractors and leaf blowers will need one later. So write the contract first, as an interface, and then have RidingMower keep it.
RidingMower is started, with its make and model.
The contract, an interface named FuelTank, has two methods:
int getFuel(): how many liters are in the tank.void addFuel(int liters): pourslitersmore into the tank.
The tank holds at most 10 liters. A new mower's tank is empty.
For example:
FuelTank tank = new RidingMower("Meadow Pro", "5500");
tank.addFuel(5);
tank.addFuel(3);
| Step | Fuel |
|---|---|
| A new mower | 0 |
addFuel(5) |
0 + 5 = 5 |
addFuel(3) |
5 + 3 = 8 |
So after those two calls, tank.getFuel() returns 8.
Your job: write the interface, then keep it in RidingMower.
- Write the interface
FuelTankwith the two methods above, with no bodies. - Make
RidingMowerimplementFuelTank. - Give
RidingMowera field for its fuel, starting at0, and write the two methods. - When more fuel is poured than fits, the tank fills to
10and the rest spills:8liters, thenaddFuel(5), makes10, not13.
Practiced live on the lesson page: write the Java right there and check it.