Java Interfaces
In this page:
What is an Interface?
An interface defines a pure contract — historically just abstract method signatures and constants — describing what a class must be able to do, without saying anything about how it does it internally.
Example: What is an Interface?
interface Drivable {
void drive(); // contract: what, not how
}
public class Main {
public static void main(String[] args) {
System.out.println("Interface declared");
}
}
Login to try C/C++/Java/PHP code in the editor
Implementing Interfaces
A class opts into an interface's contract with the implements keyword, and the compiler enforces that the class provides a concrete implementation for every abstract method the interface declares, or the class won't compile.
Example: Implementing Interfaces
interface Drivable {
void drive();
}
class Car implements Drivable {
public void drive() {
System.out.println("Driving");
}
}
public class Main {
public static void main(String[] args) {
new Car().drive();
}
}
Login to try C/C++/Java/PHP code in the editor
Interface Variables
Any field declared inside an interface is implicitly public static final, whether you write those modifiers or not, which effectively makes interface fields shared, unchangeable, global constants rather than per-instance state.
Example: Interface Variables
interface Constants {
int MAX_SPEED = 120; // implicitly public static final
}
public class Main {
public static void main(String[] args) {
System.out.println(Constants.MAX_SPEED);
}
}
Login to try C/C++/Java/PHP code in the editor
Default Methods in Interfaces
Java 8 introduced default methods, which let an interface include a fully implemented method body directly in the interface itself — this made it possible to add new methods to existing interfaces without breaking every class that already implements them.
Example: Default Methods in Interfaces
interface Greeter {
default void greet() { // implemented directly in the interface
System.out.println("Hello!");
}
}
class Person implements Greeter {
}
public class Main {
public static void main(String[] args) {
new Person().greet();
}
}
Login to try C/C++/Java/PHP code in the editor
Static Methods in Interfaces
Interfaces can also define static methods, callable directly through the interface name rather than through an implementing object, which is useful for utility helpers that logically belong with the interface but don't depend on any particular implementation's state.
Example: Static Methods in Interfaces
interface MathUtils {
static int square(int n) {
return n * n;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(MathUtils.square(5)); // called through interface name
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: