blog

Home / DeveloperSection / Blogs / Interfaces in Java: Syntax with Example code

Interfaces in Java: Syntax with Example code

Jonas Stuart 1768 18-May-2016

Interface Syntax:

An interface uses syntax similar to that of a class declaration. The format of the interface syntax is shown here:

Modifiers interface InterfaceName extends InterfaceName(s){
InterfaceBody                
}

A typical interface declaration looks like the following:

interface PrimaryColors {
int RED = 0xFF0000;
int GREEN = 0x00FF00;
int BLUE = 0x0000FF;
}

 The interface is defined using the interface keyword. The interface has a name that follows the standard naming conventions for a class declaration. The Modifiers control its visibility, which can be either public or default. Therefore, we either specify this field as public or none.

If we use a public modifier, we must put our interface definition in a separate compilation unit (a .java file). As in the case of classes, a public access modifier allows the interface to be accessed outside of the package in which it is declared.

The extends keyword has a similar meaning as in the case of a class declaration. An interface may extend another interface. When an interface extends another interface, it adds a few more constants and/or method declarations to the existing interface. However, it is not allowed to provide an implementation for any of the new methods or the methods inherited from an existing interface.

In the interface body, we declare constants and method signatures. An interface is allowed to declare constants but not variables. The declaration of a method signature in an interface is also called abstract method declaration. Because these methods do not contain any implementation, they are called abstract.

Example:

To illustrate how to declare and implement an interface, let’s look at a concrete example. Suppose we are asked to represent different kinds of vehicles in our application software. A vehicle could run on gasoline or electric batteries. Therefore, we will have two different classes of vehicles. Each type would have its own fuel-efficiency measure. For gas vehicles, it is the gasoline consumed per mile, and for electric vehicles it is the kilowatts (KW) of power consumed per mile. Because this is common functionality and must be implemented by every type of car, including those that will come on the market in the future, let’s create a standard interface that every vehicle will implement. We’ll call this interface MileageEfficiency. Any vehicle that implements this interface will get a standard set of methods for obtaining the vehicle’s efficiency. To keep things short and simple, we’ll define this interface with a single method, as follows:

interface MileageEfficiency {
public float getMilesPerGallon();
}
The GasVehicle and ElectricVehicle classes we will be writing shortly will implement this interface and provide an appropriate implementation for its sole method—getMilesPerGallon.
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 {
                     private float kwPowerConsumed;
                     private float tripCounter;
                     public float getMilesPerGallon() {
                             return tripCounter / kwPowerConsumed;
                     }
                     public void makeTrip() {
                             tripCounter = 100;
                             kwPowerConsumed = 5.6f;
                     }
}
public class TestDrive {
                     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("Efficiency of Electric Vehicle (miles/kw): %.02f%n",                                                 electricVehicle.getMilesPerGallon());                      }
}

Both the GasVehicle and ElectricVehicle classes define the MileageEfficiency interface and provide their own unique implementation for the method getMilesPerGallon. Both classes also define a method called makeTrip that records the fuel consumed and the distance traveled on a trip. The TestDrive class defines a main function that creates an instance of both the vehicles, makes a trip on each, and prints the fuel efficiency after the trip. When we run the program, we see the following output:

Efficiency of Gas Vehicle (miles/gallon): 11.76

Efficiency of Electric Vehicle (miles/kw): 17.86

Note that the MileageEfficiency interface we have created can be applied to any other vehicle type that may come in the future.


Updated 15-Mar-2018

Leave Comment

Comments

Liked By