Java Interface

In this chapter you will learn:

  1. What is a Java Interface
  2. How to define an interface
  3. Note for Java Interface
  4. How to implement an 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  a  v  a  2s.c  o m
   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 . jav a  2 s .co m*/

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.

Next chapter...

What you will learn in the next chapter:

  1. How to access implementations through interface references
  2. Example - Java Interface as data type
  3. How to use interface to do polymorphism