Java interfaces
An interface is a collection of methods that have no implementation but can be used by classes and the implementation of these methods is defined individually by classes.
This lesson focuses on:
- Declaring an interface
- Using an interface
Declaring an interface
An interface is declared with the interface keyword.
Syntax:
interface nameOfInterface{
}
Example:
interface anInterface{
}
You can add methods to an interface the same way you would add methods to a class, except the methods in an interface have no implementation.
Example:
interface anInterface{
public void printData(String data);
public String getUserInput();
}
In the above example, an interface named anInterface is declared with the method printData(String data) and getUserInput().
NOTE: Interfaces should be declared in separate files, and the name of the file an interface is declared in should have the same name as the interface (including the same capitalization!), and should have a .java extension. For example, the code for the interface from above should be in a separate file named anInterface.java
Using an interface
To use an interface use the implements keyword with the name of the interface in a class definition.
Syntax:
class nameOfClass implements nameOfInterface{
}
Example:
class AClass implements anInterface{
}
In the above example, a class named AClass calls the anInterface interface. The aClass class can now use the methods declared in the anInterface interface and define their implementation.




