So what is a Java interface? It’s actually a really good question because I have found many Java programmers that have never used an interface in their Java programming activities. I suspect this is the case because maybe they don’t understand the concept and benefit of an interface.
A Java interface is similar to a Java class. However, a Java interface can only contain method signatures and data fields. A Java interface can define methods, including the input and output, but not contain the actual implementation code within the method. Let’s take a look at the sample Java Interface below.
Define Java Interface
We have defined a simple interface that contains a variable called “greeting”. It also contains two methods: jcdGreeting() and jcdRoundIt().
public interface JavaCodeDepotInterface
public String greeting = "Java Code Depot Intefface Says Hello";
public void jcdGreeting();
public void jcdRoundIt(int number);
All of the methods in an interface are public and abstract. In order for you to implement an interface, the implementing class do the following:
- It must use the Java implements clause for class declaration.
- It must implement every method declared within the interface.
Implement Java Interface
As you see below, the variable “greeting” can be accessed directly from the interface. When implementing the methods, the class must use the same format as what is defined in the interface for each method.
public class JavaCodeDepotInterfaceImpl implements JavaCodeDepotInterface
public void jcdGreeting()
int number = 999;
public void jcdRoundIt(int number)
Why Use Java Interfaces?
Implementing an interface in Java allows the class to be more formal about the behavior of the methods within the interface. Think of this as a contract between the class and the world. This contract is enforced at build time by the compiler. If your implementing an interface, all methods defined by the interface must appear in the source code before the class will successfully compile.