Interfaces in Java

Now let us try to understand interfaces in Java. Interfaces provide specification or standard. They tell what must be done. But they do not specify how it is to be done or implemented. Another class has to provide the implementation. Interfaces kind of create a standard set of methods as all classes implementing that interfaces must implement method with the same name.

Interfaces are like Classes in terms of syntax.  Major difference between interfaces and classes are –

  1. Interfaces contain only declaration of method. Concrete classes must have definitions of the methods. Abstract classes may contain undefined methods.
  2. An interface can extend another interface (not a class) and can implement multiple interfaces. A class can implement multiple interfaces but can just extend one class.
  3. All members of Interface are public by default.
  4.  Interfaces variables are final and static by default.
  5. All methods of the Interface are abstract by default.

Example – In below example, we have a Movable interface with one method declaration move() and a variable MAX_SPEED. Class Bike implements that interface by providing definition of the method move().

Interfaces in Java



package oops;

/**
 * Created by Sagar on 16-04-2016.
 */
public class interface_implementation {
    public static void main(String [] args){
        Bike kawasaki = new Bike();
        kawasaki.move();
    }
}

class Bike implements Movable{
    @Override
    public void move() {
        System.out.println("Move implementation");
        System.out.println("Max speed can be -> " + Movable.MAX_SPEED);
    }
}

interface Movable {
    int MAX_SPEED = 100;
    void move();
}

Here is the output of Above Java example.

Move implementation
Max speed can be -> 100

You may also like...