Java Interface

In this chapter you will learn:

  1. What is a Java Interface
  2. How to define an interface
  3. How to implement an interface

What is a Java Interface

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.

Defining an Interface

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); 
   //j a v  a2  s. c  om
   type final-varname1 = value; 
   type final-varname2 = value; 
   
   // ... 
   return-type method-nameN(parameter-list); 
   
   type final-varnameN = value; 
}

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);
}/*from   j a v a 2s .c o  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. How to use interface to do polymorphism