Software >> Programming >> Java >> Language >> What is an interface

 

It is a reference type similar to a class, but contains only declarations of methods and properties but not their implementation. 

A class that implements an interface must have all the methods of the interface and define them in it's code.  All methods must be implemented before it can successfully compile.

The interface forms a contract between the class and the outside world.

Example

interface Bicycle { void changeGear(int newValue); void applyBrakes(int decrement); }

class XyzBicycle implements Bicycle {
    int gear = 1;
    void changeGear(int newValue) {
         gear = newValue;
    }
    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }
    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}

References

[1] docs.oracle.com/javase/tutorial/java/concepts/interface.html