Monday, 20 October 2014

Interface

An interface defines a contract which has to be implemented by a class. The implementation of an interface should strictly follow the contract: polymorphism is not allowed. 

An interface has either 'default' or 'public' access modifier and can declare public methods and constants. A method can not be declared with any modifiers, except public.
interface Animal{
   public void setAnimal(Animal a);
}

class Dog implements Animal{
   public void setAnimal(Animal a) { // Ok
       System.out.println("Dog");
   }
}

class Cat implements Animal{
   // Won't compile, even if "Dog" IS-AN "Animal"
   public void setAnimal(Dog a) {
       System.out.println("Cat");
   }
}

Note that for the compiler each method is "public abstract" and each constant is "public static final".
public interface Car {

   // same than 'public static final float mileToKm = 1.6;'
   float mileToKm = 1.6;

   // same than 'public int getMaxSpeed();'
   int getMaxSpeed();

   // same than 'public float getMileage();'
   foat getMileage();
}

Very important: a class which implements an interface should implements all its methods by explicitly marking them as public.
public class Renault implements Car {

   public int getMaxSpeed(){
      return 220;
   }

   public float getMileage(){
      // I use the interface's constant as it was part of the class 'Renault'
      mileToKm * 83000;
   }

}