Interfaces are a key concept in object oriented programming. They serve as a template to insure that all derived classes implement the methods declared in the interface.
Interfaces must never define the method, they only declare it. This is one of the major differences between an interface and an inherited class. The other major difference is that unlike an inherited class a derived class may implement as many interfaces as is needed.
In this simple example we create an interface — Wheel — that declares two methods, tire and rim. These methods must be defined within the implementing class, Car. We can then create a new instance of a Car and call the methods we’ve created, adding the necessary arguments.
You may ask yourself why we would want to create an interface, why not just create the Car class and omit the Wheel interface. The reason we create interfaces is to ensure that the derived class implementing the interface creates all the methods necessary for the interface. If we have a truck, a trailer, an SUV all will need wheels and by implementing the wheel they must define the methods. Interfaces are a blueprint of the necessary functionality that must be implemented in the derived class.
interface Wheel {
public void tire(String brand);
public void rim(String brand);
}
class Car implements Wheel {
public void tire(String brand) {
System.out.printf("Tire Brand: %s \n", brand);
}
public void rim(String brand) {
System.out.printf("Rim Brand: %s ", brand);
}
}
class MyMainClass {
public static void main(String[] args) {
Car porche = new Car();
System.out.println("Car Wheel: ");
porche.tire("Good Year");
porche.rim("Titan");
}
}