Interface

Interface
An interface is a java exclusive type of class that is usually only made up of methods. It can declare data types but any object declared will be static. All methods in an interface are public and don't do anything in the actual interface file. So by now you might be asking what the heck am I supposed to use this for. And I would answer planning my good friend. Before I continue with the uses of interfaces I need to start an analogy. //Think of your program like a modular space station. With your structure hanging in space you have the option to add new components over time. The big concern with your space station is future extensibility and functionality. You need to be able to replace old modules as they wear out without recreating the entire space station. The interface is what holds your station together.// Interface also fix another problem dealing with inheritance. In Java you can only extend one class per class, no class can have more than one parent. Suppose you create a zombie class that inherits from classes Humanoid, Thing, and Undead. Since Java only supports single inheritance for classes, you might try to achieve the goal by having an inheritance chain like this: Zombie, Undead, Humanoid, Thing. But not all of your Undead entities are Humanoid, the VampireBat being a case in point, so you try this instead: Zombie, Humanoid, Undead, Thing. Now all subclasses of Humanoid are also Undead and this also violates the consistency of your polymorphic relationships. The solution to this is to use multiple interface inheritance instead, which Java supports. Did I mention interfaces can also extend other interfaces.

Finally to an example: code format="java" public class Main{ interface AreaCompare{ //our interface int compare(AreaCompare o); float getArea; }   class Square implements AreaCompare{ float length, width; Square(float l, float w){ length = l;           width = w;        } int compare(AreaCompare o){ return o.getArea < getArea ? -1: 1;       }        float getArea{ return length * width; }   }    class Circle implements AreaCompare{ static float PI = 3.141592f; float radius; Square(float r){ radius = r;       } int compare(AreaCompare o){ return o.getArea < getArea; }       float getArea{ return PI*r*r; }   }    class Triangle implements AreaCompare{ float base, height; Square(float b, float h){ base = b;           height = h;        } int compare(AreaCompare o){ return o.getArea < getArea; }       float getArea{ return 0.5f*base*height; }   }    public static void main(String[] args){ AreaCompare[] set = { new Square(5, 5), new Circle(5), new Triangle(5, 5) }; Cirlce circle = new Circle(5); for(AreaCompare o: set){ String str = o.comare(circle) == -1 ? "smaller" : "larger"; System.out.println("This object is " + str + " than my circle."); }   } } code