What is a Java Interface

Description

interface specifies what a class must do, but not how it does it.

An interface in Java is like a contract. It defines certain rules through Java methods and the class which implements that interface must follow the rules by implementing the methods.

To implement an interface, a class must create the complete set of methods defined by the interface.

Syntax

An interface is defined much like a class. This is the general form of an interface:


access interface name { 
   return-type method-name1(parameter-list); 
   return-type method-name2(parameter-list); 
   //from w  w  w. j av a2s. c  om
   type final-varname1 = value; 
   type final-varname2 = value; 
   
   // ... 
   return-type method-nameN(parameter-list); 
   
   type final-varnameN = value; 
}

Note

Variables can be declared inside of interface declarations. They are implicitly final and static. Variables must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public.

Here is an example of an interface definition.


interface MyInterface{ 
   void callback(int param); 
}

Implementing Interfaces

To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface.

The general form of a class that includes the implements clause looks like this:


access-level class classname [extends superclass] [implements interface [,interface...]] { 
   // class-body 
}

Here is a small example class that implements the interface shown earlier.

 
interface MyInterface {
  void callback(int param);
}/*  w w w. j  a va 2  s.com*/

class Client implements MyInterface{
  // Implement Callback's interface
  public void callback(int p) {

    System.out.println("callback called with " + p);
  }
}

callback() is declared using the public access specifier. When you implement an interface method, it must be declared as public.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures