Java 101: Interfaces in Java

Spread the love

Java interfaces are different from classes, and it’s important to know how to use their special properties in your Java programs. This tutorial introduces the difference between classes and interfaces, then guides you through examples demonstrating how to declare, implement, and extend Java interfaces.

You’ll also learn how the interface has evolved in Java 8, with the addition of default and static methods, and in Java 9 with the new private methods. These additions make interfaces more useful to experienced developers. Unfortunately, they also blur the lines between classes and interfaces, making interface programming even more confusing to Java beginners.

What is a Java interface?

An interface is a point where two systems meet and interact. For example, you might use a vending machine interface to select an item, pay for it, and receive a food or drink item. From a programming perspective, an interface sits between software components. Consider that a method header (method name, parameter list, and so on) interface sits between external code that calls the method and the code within the method that will be executed as a result of the call. Here’s an example:

System.out.println(average(10, 15));
double average(double x, double y) // interface between average(10, 15) call and return (x + y) / 2;
   return (x + y) / 2;