Skip to main content Skip to docs navigation
TechSpiderTutorials

Interfaces in Java

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

Defining an Interface

An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body.

Example:

public interface GroupedInterface extends Interface1, Interface2, Interface3 
{
// constant declarations

// base of natural logarithms
double E = 2.718282;

// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}

The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package as the interface.

The Interface Body

The interface body can contain default methods, abstract methods and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers

Implementing an Interface

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

interface Interface1 
  {

  }
interface Interface2 
  {

  }

class Sample implements Interface1,Interface2,...
{

-------
-----
--------
}
  • A class can extend only one other class, an interface can extend any number of interfaces.
  • All methods declared in an interface are implicitly public, so the public modifier can be omitted.
  • An interface can contain constant declarations in addition to method declarations.
  • All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.
  • Note: All of the methods in an interface are implicitly abstract, so the abstract modifier is not used with interface methods