When you’re learning Java, one concept that keeps popping up is interfaces. You’ll see them used in frameworks, design patterns, and of course, in technical interviews.
So, what exactly are interfaces in Java?
In simple terms, interfaces define what needs to be done without saying how it should be done. They let you set rules and contracts that other classes agree to follow. If a class says, “I implement this interface,” it’s promising to do what the interface says.
In this guide, we’ll explore what interfaces are, why they’re useful, and how you can start using them in your own Java projects.
Table of Contents:
What is an Interface in Java
In Java, an interface is a type that’s a lot like a class but with a twist. Instead of defining behavior, it simply outlines it. An interface in Java tells you: “What needs to be done,” but it doesn’t explain how to do it. That part is left up to the class that implements it.
So think of it as a blueprint. It can include method signatures, constants, default methods, static methods, and even nested types. But what it can’t include are instance fields or constructors.
Syntax of Interface in Java
Now that you’ve got the big picture of what interfaces are and why they matter, let’s look at the actual syntax.
Here’s a simple example of how to define an interface:
interface Vehicle {
void start();
void stop();
}
This interface defines two method signatures: start() and stop(). There’s no code inside them, just the method names, return types, and parameters.
That’s because interfaces don’t handle the how part; it simply says that if you implement, make sure these methods exist.
Any class that implements this Vehicle interface will need to provide real code for both methods, and we’ll cover that in the next section.
Let’s break it down with a quick example:
Example:
Output:
Here, the Animal interface defines a method called makeSound(). Both Dog and Cat implement the interface and provide their own versions of that method. The structure stays the same, but the behavior changes depending on the class.
Why Use Interfaces in Java?
Interfaces might sound a bit abstract at first, but they solve real-world problems and make your code easier to manage in the long run. Here’s why developers use them so often:
- Abstraction: You get to focus on what should be done, not how. That keeps your code clean, reusable, and easy to understand.
- Multiple Inheritance: Java doesn’t let a class inherit from more than one class, but it does let you implement multiple interfaces. This lets you mix behaviors without the mess of multiple class inheritance.
Output:
- Loose Coupling: Interfaces help you build systems where parts don’t depend too tightly on each other. That makes your code easier to test, extend, or swap out later.
- Polymorphism: You can treat different classes the same way, as long as they implement the same interface. That’s powerful when writing reusable logic.
void makeAnimalSound(Animal animal){
animal.makeSound();
}
Types of interfaces in Java
Now that you know what an interface is, let’s look at the different kinds Java provides.
1. Normal Interface
This is the most common type of interface in Java. It just contains method declarations (abstract methods) and constants.
interface Drawable {
void draw();
}
2. Functional Interface
A functional interface contains exactly one abstract method. It’s used heavily in lambda expressions and functional programming, introduced in Java 8.
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
3. Marker Interface
This type of interface has no methods or fields at all. It simply marks a class with metadata. For example:
interface Serializable {}
The JVM checks for this marker to know if an object can be serialized.
Implementing Interfaces in Java
Once you’ve defined an interface, the next step is to use it by implementing it in a class. This is where the real logic lives.
1. Basic Implementation
Here’s a quick refresher:
Output:
Here, InkjetPrinter promises to follow the rules defined by the Printer interface. It provides the actual behavior for printDocument(). If it didn’t, the compiler would throw an error.
2. One Interface, Many Implementations
One of the best things about interfaces is that they support multiple implementations. You can define behavior differently depending on what the class needs to do.
Output:
Now, whether you’re printing to paper or saving as a file, all these classes can be treated as a Printer. This helps build flexible, interchangeable components.
3. Using Interface References
Here’s where things get even more useful. You can store any object that implements Printer in a variable of type Printer.
Printer printer = new LaserPrinter();
printer.printDocument("Test page");
This is a clean example of polymorphism; you don’t need to know the exact type of printer as long as it follows the contract, your code works.
Implementing interfaces is simple in syntax, but incredibly powerful in design. Up next, we’ll explore how Java allows a class to implement multiple interfaces and why that’s useful.
Interface Inheritance
Similar to classes in Java, interfaces can extend other interfaces. This is known as interface inheritance. This helps you build specific types by reusing existing interfaces without starting over.
When one interface extends another, it inherits all the method signatures. You can then add more methods on top of that.
interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
}
In this case, Pet extends Animal, so it includes both eat() and play(). Any class that implements Pet needs to define both methods.
Output:
So even though Dog only implements Pet, it still has to follow the full contract, Pet, and everything it extends.
Multiple Inheritance Using Interface in Java
In Java, a class can’t extend more than one class, but it can implement multiple interfaces. That’s Java’s way of supporting multiple inheritance, without the complications.
Why This Matters:
- No multiple class inheritance: Java avoids the “diamond problem” by not allowing a class to extend more than one class.
- Interfaces fix that: Since interfaces only define method signatures (no actual code), a class can safely implement several of them at once.
- More flexibility: You can build small, focused interfaces and let classes combine them as needed.
Example:
Output:
Here, the Smartphone class combines two separate behaviors, camera and GPS, by implementing both interfaces. This approach keeps things modular and easy to maintain.
Functional Interfaces in Java
A functional interface in Java is just what it sounds like: an interface with a single job. More specifically, it has only one abstract method. That simplicity is what makes it powerful.
These interfaces became especially useful in Java 8 when lambda expressions were introduced. Lambdas let you pass around behavior, like data. They’re short, expressive, and they only work with functional interfaces.
1. What Makes an Interface “Functional” in Java?
To be a functional interface, it must have exactly one abstract method. It can still include default or static methods, but there can only be one abstract one.
Here’s an example:
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
You don’t have to use the @FunctionalInterface annotation, but it’s a good idea as it makes the intention clear and helps catch errors early.
2. Why Should You Use Them?
Functional interfaces let you pass behavior around, just like variables. That means less boilerplate and more readable code. It also brings Java a little closer to functional programming styles.
3. Example Using a Lambda
Output:
Instead of creating a full class that implements Greeting, you just define what it does right there. It’s clean, expressive, and easier to maintain.
4. Built-In Functional Interfaces
Java comes with a bunch of ready-made functional interfaces in the java.util.function package:
- Supplier<T>: returns a value
- Consumer<T>: takes a value, returns nothing
- Function<T, R>: takes input and returns output
- Predicate<T>: returns true or false
These are the backbone of Java’s newer APIs, like Streams and Optional. If you’ve seen them before and weren’t sure what they were, now you know, they’re just functional interfaces behind the scenes.
New Features in Interfaces
Back in the day, before Java 8, interfaces were pretty limited. You could only define abstract methods and constants. No method bodies, no logic, just a contract. That changed with Java 8 and Java 9, and interfaces became much more flexible and powerful. With Java 8 and Java 9, interfaces became much more powerful and flexible.
1. Default Methods (Java 8)
A default method is a method in an interface that comes with a body. You can think of it as a backup implementation. If a class doesn’t override it, the default version runs.
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting…");
}
}
This helps when you want to add new methods to an existing interface without breaking all the classes that already use it.
2. Static Methods (Java 8)
You can also define static methods in interfaces. These are utility-style methods that belong to the interface itself, not to any instance.
interface MathUtils {
static int square(int x) {
return x * x;
}
}
To call it: MathUtils.square(5);
3. Private Methods (Java 9)
Java 9 added private methods to interfaces. These aren’t accessible outside the interface; they’re used to keep your default and static methods clean and DRY (Don’t Repeat Yourself).
interface Logger {
default void logInfo(String msg) {
log("INFO: " + msg);
}
private void log(String msg) {
System.out.println(msg);
}
}
Think of private methods as a way to avoid repeating yourself within the interface.
4. Extending Multiple Interfaces
An interface can also extend multiple interfaces in Java. And since interfaces don’t include implementation (unless you’re using default methods), you don’t run into the classic “diamond problem.”
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
interface Amphibious extends Flyable, Swimmable {}
Now, any class that implements Amphibious will be expected to provide both fly() and swim() methods.
Real-World Java Interface Examples
So far, we’ve looked at what interfaces are and how they work. But where do they actually show up in real Java projects? The short answer: everywhere.
Interfaces are baked into many parts of the Java standard library. You’ve probably used some without even realizing it.
List<String> names = new ArrayList<>();
Set<Integer> numbers = new HashSet<>();
You can easily switch between implementations because your code depends on the interface, not the class.
- Comparable and Comparator: These interfaces are used for sorting. You’ll find them in almost every Java application that handles lists or custom objects.
- Runnable: Used for multithreading. When you want to run code on a separate thread, you pass a class that implements Runnable.
Output:
- Event listeners in GUI applications: If you’ve ever worked with Swing or JavaFX, you’ve seen interfaces like ActionListener, which respond to user events like button clicks.
Advantages and Disadvantages of Interfaces in Java
Interfaces are powerful, but like any tool, they come with both strengths and trade-offs. Here’s a quick overview:
Advantages |
Disadvantages |
Help you focus on what to do, not how to do it |
Can’t store state; no instance variables allowed |
Let you combine multiple behaviors with ease |
Too many interfaces can make the codebase harder to manage |
Make your code loosely coupled and easier to test |
All methods are public, so there’s less control over access |
Works well across unrelated classes, thanks to polymorphism |
You can’t create objects from interfaces directly |
Keep your code flexible and open to future changes |
Older versions of Java didn’t support default method bodies |
Interfaces shine when you’re designing flexible systems, reusable components, or defining contracts for future development. Just be careful not to over-engineer with too many tiny interfaces.
Difference Between Interfaces, Classes, and Abstract Classes
Java gives you three main ways to structure your code: interfaces and classes. Here’s how they compare:
Feature |
Interface |
Class |
Can be instantiated? |
No |
Yes |
Can have method bodies? |
Yes (default/static/private) |
Yes |
Can define constructors? |
No |
Yes |
Supports multiple inheritance |
Yes (via multiple interfaces) |
No |
Can have instance variables? |
No (only constants) |
Yes |
Inheritance keyword |
implements |
extends |
Use case |
Define what to do |
Complete implementation |
When to Use Which
- Interface: When you want to define a contract that multiple unrelated classes can follow.
- Class: When you have a full implementation and no need for inheritance or abstraction.
Java Interface Interview Questions
If you’re preparing for a Java interview, expect questions about interfaces; they’re a favorite topic. Here are some common ones, along with answers that keep things clear and to the point:
1. What is an interface in Java?
Think of it as a contract. An interface defines what a class should do, without saying how to do it. It’s used to build loosely coupled systems and support abstraction.
2. Can an interface have method implementations?
Yes! Since Java 8, interfaces can include default and static methods with actual code. Java 9 added private methods, which help organize logic within the interface itself.
3. How is an interface different from an abstract class?
- Interfaces don’t have constructors or instance variables.
- Abstract classes can hold state and provide partial implementations.
- Java allows multiple interface inheritance, but not multiple class inheritance.
4. Can you create an object of an interface?
No. Interfaces don’t have constructors. But you can use them as reference types for objects of implementing classes.
5. What happens if a class doesn’t implement all the methods of an interface?
The class must be declared as abstract. Otherwise, the compiler will throw an error.
6. Can interfaces have instance variables?
Not really. Interfaces can only contain constants; these are implicitly public, static, and final. You can’t have regular instance variables.
7. Can an interface extend another interface?
Yes. And it can extend multiple interfaces, too. The new interface will inherit all method signatures from its parent(s).
8. What’s the difference between a class and an interface in Java?
The main differences between a class and an interface are:
Feature |
Class |
Interface |
Can be instantiated? |
Yes |
No |
Can have method bodies? |
Yes (including constructors) |
Only from Java 8 onward (default/static methods) |
Can have instance variables? |
Yes |
No (only constants – public static final) |
Inheritance rules |
Can extend one class |
Can implement multiple interfaces |
Purpose |
Defines both what and how (behavior + implementation) |
Defines only what to do (behavior, no implementation) |
Conclusion
Interfaces are one of Java’s most important features. They help you write flexible, maintainable, and scalable code by defining what needs to be done, without locking in how it should be done. If you want to learn more about Java interfaces and other advanced topics, check out our Java certification course.