articles

Home / DeveloperSection / Articles / Interfaces in Java: Implementing Multiple Interfaces

Interfaces in Java: Implementing Multiple Interfaces

zack mathews 1949 19-May-2016

In the previous post, we created a standard interface to get the fuel efficiency of a car. A car has many such standard functions that could be defined in terms of interfaces. For example, we could define interfaces for steering, braking, refilling, and so on. We’ll now create one such interface for tracking the remaining battery life of electric and hybrid vehicles. Obviously, this interface is of no use to a car that runs on gasoline. Therefore, only electric and hybrid cars will implement our new interface. Let’s call this interface BatteryLifeTracker. The interface definition is shown in the following code snippet:

interface BatteryLifeTracker {

     final int MAX_NUMBER_OF_RECHARGES = 300;
     public void chargeBattery();
     public int getRemainingLife();
}

 The BatteryLifeTracker interface defines a constant that specifies the maximum number of times the car battery can be charged. It also defines a standard interface method called chargeBattery that increments the charge counter. The getRemainingLife method returns the number of times the battery can still be charged before it is rendered useless. Both ElectricVehicle and HybridVehicle classes implement this interface. The class declaration now looks like this:

class ElectricVehicle implements MileageEfficiency, BatteryLifeTracker {

Note that the two interface names are separated with a comma. As a matter of fact, we could have any number of interfaces listed here, each separated with a comma. For each interface, we must implement all its methods within the class body.

Both ElectricVehicle and HybridVehicle now declare a static counter called numberOfRecharges to keep record of how many times the battery has been charged:

private static int numberOfRecharges;

The implementations of the chargeBattery method in these classes simply increment this charge count. The implementation of the getRemainingLife method returns the difference between the total charge count and the number of times the battery has been charged so far. The main method prints this useful battery life information for both the cars. The complete program is given here:

interface MileageEfficiency {
                     public float getMilesPerGallon();
}

interface ExtendedMileageEfficiency extends MileageEfficiency {
                     public float getFuelEfficiency();
                     public float getElectricEfficiency();
}
interface BatteryLifeTracker {
                     final int MAX_NUMBER_OF_RECHARGES = 300;
                     public void chargeBattery();
                     public int getRemainingLife();
}
class GasVehicle implements MileageEfficiency {
                     private float fuelConsumed;
                     private float tripCounter;
                     public float getMilesPerGallon() {
                             return tripCounter / fuelConsumed;
                     }
                     public void makeTrip() {
                             tripCounter = 100;
                             fuelConsumed = 8.5f;
                     }

}

class ElectricVehicle implements MileageEfficiency, BatteryLifeTracker {
                     private float kwPowerConsumed;
                     private float tripCounter;
                     private static int numberOfRecharges;
                     public float getMilesPerGallon() {
                             return tripCounter / kwPowerConsumed;
                     }

                     public void makeTrip() {
                             tripCounter = 100;
                             kwPowerConsumed = 5.6f;
                     }

                     public void chargeBattery() {
                             numberOfRecharges++;
                     }
                     public int getRemainingLife() {
                             return MAX_NUMBER_OF_RECHARGES - numberOfRecharges;
                     }
}

class HybridVehicle implements ExtendedMileageEfficiency, BatteryLifeTracker {
                     private float tripCounter;
                     private float fuelConsumed;
                     private float kWPowerConsumed;
                     private static int noOfRecharges;
                     public float getFuelEfficiency() {
                             return tripCounter / fuelConsumed;
                     }
                     public float getElectricEfficiency() {
                             return tripCounter / kWPowerConsumed;
                     }
                     public float getMilesPerGallon() {
                             return 0.8f * getFuelEfficiency() + 1.12f % getElectricEfficiency();
                     }

                     public void makeTrip() {
                             tripCounter = 100;
                             fuelConsumed = 4.1f;
                             kWPowerConsumed = 3.4f;
                     }

                     public void chargeBattery() {
                             noOfRecharges++;
                     }
                     public int getRemainingLife() {
                             return MAX_NUMBER_OF_RECHARGES - noOfRecharges;
                     }
}
public class FurtherEnhancedTestDrive {
                     public static void main(String[] args) {
                             GasVehicle gasolineVehicle = new GasVehicle();
                             gasolineVehicle.makeTrip();
                             System.out.printf("Efficiency of Gas Vehicle (miles/gallon): %.02f%n",
                                                gasolineVehicle.getMilesPerGallon());
                             ElectricVehicle electricVehicle = new ElectricVehicle();
                             electricVehicle.makeTrip();
                             System.out.printf(
                                                "%nEfficiency of Electric Vehicle (miles/kw): %.02f%n",
                                                electricVehicle.getMilesPerGallon());
                             for (int i = 0; i < 78; i++) {
                                      electricVehicle.chargeBattery();
                             }
                             System.out.printf("The battery can be charged %d more times%n",
                                                electricVehicle.getRemainingLife());
                             HybridVehicle hybridVehicle = new HybridVehicle();
                             hybridVehicle.makeTrip();
                             System.out.printf("%nEfficiency of hybrid Vehicle "
                                                + "(miles/EnergyConsumed): %.02f%n",
                                                hybridVehicle.getMilesPerGallon());
                             for (int i = 0; i < 15; i++) {
                                      hybridVehicle.chargeBattery();
                             }
                             System.out.printf("The battery can be charged %d more times%n",
                                                hybridVehicle.getRemainingLife());
                     }

}

 Output:

When we run the program, the following output is produced:

Efficiency of Gas Vehicle (miles/gallon): 11.76
Efficiency of Electric Vehicle (miles/kw): 17.86
The battery can be charged 222 more times
Efficiency of hybrid Vehicle (miles/EnergyConsumed): 20.63
The battery can be charged 285 more times


 
Combining Interfaces

Java does not allow us to extend a class from more than one class. However, we can create an interface that extends one or more interfaces. For example, we could add a new interface that provides a method for computing the efficiency of a car irrespective of whether it runs on gasoline or a battery. Such an interface is declared as follows:

interface EfficiencyCalc extends MileageEfficiency, BatteryLifeTracker {

public float getCarEfficiency();

}

Any class that implements EfficiencyCalc has to provide the implementation not only for the getCarEfficiency method but also for all the inherited methods of MileageEfficiency and BatteryLifeTracker. Implementing multiple interfaces like this allows them to inherit the behavioural protocols of the parent interfaces.

A Few Important Points on Interfaces

Here are a few important points we should keep in mind concerning interfaces:

·   An interface is very similar to a class, except that it can have only fields that are implicitly public and static and method declarations that are implicitly public and abstract.

·   The Java API documentation lists interfaces like classes.

·    The interfaces compile to a .class file and get loaded by the same process that loads classes.

·     We can create a reference variable whose type is the interface name. Only the methods defined in an interface will be visible through this reference.

·    Any constants defined by an interface can be accessed without a prefix from code within the class because implementing the interface makes them part of the implementing class.


Updated 16-Dec-2017

Leave Comment

Comments

Liked By