Java interfaces
An interface is a collection of methods that have no implementation - they are just created, but have no functionality. What's the purpose of such methods? For you to define their functionality individually in different classes. An interface is abstract, and you define how it's elements (methods) work according to your needs.
This tutorial focuses on:
- Different Java interfaces
- Declaring an interface
- Using an interface
Different Java interfaces
Java provides many different interfaces for a wide variety of functionality.
- WindowListener - Provides methods for indicating what happens when window actions such as minimizing, resizing, and closing occur. Located in the java.awt.event package.
- ActionListener - Provides methods for indicating what happens when action events such as the clicking of a button occur. Located in the java.awt.event package.
- AudioClip - Provides methods for playing sounds. Located in the java.applet package.
Declaring an interface
While Java provides interfaces for you to use, you can also create your own.
An interface is declared with the interface keyword.
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.
Just like regular Java programs, interfaces should be declared in separate files, 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 DataManager.java
Using an interface
To use an interface, use the implements keyword with the name of the interface in the class declaration line in your code. You specify that a class implements the interface and you define in that class what the methods from the interface do.
The ClassOne class can now use the methods declared in the DataManager interface and define their functionality.
NOTE: Remember to always import the package that contains the interface you are implementing like in the example below.