Here is an example of an interface definition.
It declares an interface that contains one method called callback()
.
callback()
takes a single integer parameter.
interface Callback { void callback(int param); }
One or more classes can implement the interface.
To implement an interface, include the implements
clause in a class definition.
We need to create the methods required by the interface in the class.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interfaceName [, interfaceName...]] { // class-body }
If a class implements more than one interface, the interfaces are separated with a comma.
If a class implements two interfaces with the same method, the method will be used by either interface.
The methods that implement an interface must be declared public.
The signature of the implementing method must match the signature from the interface definition.
Here is a small example class that implements the Callback interface shown earlier:
class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } }
The following example calls the callback()
method via an interface reference variable:
public class Main{ public static void main(String args[]) { Callback c = new Client(); c.callback(42); } }
If a class implements an interface without fully implementing the methods from the interface, that class must be declared as abstract.
For example:
abstract class Incomplete implements Callback { int a, b; //from w ww. j a va2 s. com void show() { System.out.println(a + " " + b); } //this method is commented out, not in the implementation //public void callback(int p) { // System.out.println("callback called with " + p); //} }
Nested Interfaces
An interface can be declared as a member of a class or another interface.
Such an interface is called a member interface or a nested interface.
A nested interface can be declared as public, private, or protected.
A top-level interface must either be declared as public or use the default access level.
When using a nested interface outside of its enclosing scope, it must be qualified by the name of the class or interface.
// This class contains a member interface. class A { //from ww w . java 2s. c om // this is a nested interface public interface MyNestedInterface { boolean check(int x); } } // B implements the nested interface. class B implements A.MyNestedInterface { public boolean check(int x) { return x < 0 ? false: true; } } public class Main { public static void main(String args[]) { // use a nested interface reference A.MyNestedInterface nif = new B(); if(nif.check(10)) { System.out.println("10 is not negative"); } if(nif.check(-12)) { System.out.println("12 is negative"); } } }