An interface specifies the behaviours that should be present within all classes that implement (use) it. An interface contains method signatures only. There is no method implementation - there is no method body. See class diagram below:
Each behaviour defined in the interface must be implemented (coded) in any classes that implement (use) it.
The implements keyword is used to implement an interface in a class. The figure below shows the class declaration for the Person class which has been modified to implement the class called IPerson.
Interface naming convention
The naming convention for an interface is a capital I followed by a meaningful name. As the interface in this example was only designed to be used with the Person class, I have called it IPerson.
Why use an interface?
Interfaces provide a standard and consistency for communication between classes and other parts of a system.
Consider the teacher who gives her students the outline for the functional requirements of a system. Each student produces a design and implementation but has perhaps forgotten to include methods, method parameters or simply used different spelling for method names. The student adds the teachers test harness to the code but is immediately faced with compilation errors due to misspelling & missing detail.
For the next project however, as well as giving the students the functional requirements of a system, the teacher also gives them a number of interfaces to develop to, ensuring that all methods, method parameters & spelling, as used by the test harness, will be implemented in the students code.
Multiple interfaces
A class may implement many interfaces.
In the diagram above, the Weapon class implements both the IStats and IBattle interface. This means that the Weapon class must implement the methods which are present in both interfaces.
The Weapon class can now be used in the context of IStats and IBattle type.
Interface as type
Where a class implements an interface, objects of that class may be treated as objects of the interface type.
For instance:
ArrayList<IBattle> battleObjectList = new ArrayList<IBattle>();
battleList.add(new weapon);
battleList(new Arena());
All objects in the list have the context of IBattle and only the methods specified in the IBattle interface are accessible.
Java Interfaces
As well as the interface types you will write yourself, there are numerous predefined interface types in the Java API such as MouseListener, List, Map.
See also:
"What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)" ( http://bit.ly/Rph8eP )