← Back to Core Java Course | Chapter 9: OOP Advanced | Lesson 4 of 8

Java Interfaces

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?

java
interface Drivable {
	void drive(); // contract: what, not how
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Interface declared");
	}
}

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

java
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();
	}
}

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

java
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);
	}
}

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

java
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();
	}
}

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

java
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
	}
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.