Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Implementing Java Interfaces

Recommended resources

Introduction

In our last session, we saw how the final keyword allows us to enforce constraints, creating constants and preventing changes to methods and classes. Today, we shift from imposing restrictions to defining possibilities. We will explore one of the most fundamental and powerful concepts in Java and object-oriented design: interfaces.

This lesson is your formal introduction to the idea of a "contract" in programming. You will learn how to define a Java interface, which specifies a set of methods that a class must implement, and then how to create a class that fulfills this contract. Understanding interfaces is not just a Java-specific skill; it's a cornerstone of building flexible, decoupled, and maintainable software—the very goal of the design patterns we will study throughout this course.


The Interface as a Contract

At its heart, an interface is a contract. It declares what a class can do, without specifying how it does it. Imagine a contract for a "drivable" vehicle. The contract would state that any drivable vehicle must be able to startEngine(), accelerate(), and brake(). It doesn't care if it's a gasoline car, an electric car, or a hovercraft; as long as a class implements these capabilities, it fulfills the "drivable" contract.

This separation of "what" (the interface) from "how" (the implementation) is a form of abstraction, a core principle of good software design.

The following video from JavaTutorialTV provides an excellent analogy for this concept.

Java Interface - With example

This short tutorial uses a Vehicle example to explain the concept of an interface as a contract between a class and the outside world.

Please watch the first part of the video, from the beginning up to the explanation of advantages. This will ground your understanding of an interface as a contract.


Defining and Implementing an Interface

Now, let's translate this concept into Java code. You define an interface using the interface keyword. Inside, you declare methods without a body (these are implicitly public and abstract). You can also define constants (which are implicitly public, static, and final—a direct link to our previous lessons!).

A class then uses the implements keyword to agree to this contract. When it does, the Java compiler enforces the contract: the class must provide a concrete implementation for every method declared in the interface.

Let's look at the syntax and a simple example.

Guide to Interfaces in Java - Medium

This article from Medium provides a clear, step-by-step guide. We'll focus on the basic syntax and implementation.

First, read Section 2, "Syntax of Interfaces", to understand how to declare an interface and its methods. Next, read Section 4, "Implementing Interfaces". This section shows how the implements keyword is used and provides a complete Animal/Dog example. Pay attention to the @Override annotation—it's good practice to use it to indicate you're fulfilling an interface contract.

To see this process in a more dynamic way, let's return to the Vehicle example from the video. The following segment shows the programmer defining the Vehicle interface and then creating a HondaAccord class that implements it. Notice how the development environment (Eclipse) flags an error until all the methods from the interface are implemented.

Java Interface - With example

We'll continue with the JavaTutorialTV video.

Watch the segment from this timestamp. It's a great practical demonstration of the compiler enforcing the interface's contract.


The Power of Interfaces: Multiple Inheritance

Here we arrive at a crucial feature. In Java, a class can only extend one other class (single inheritance). This can be limiting. What if an object needs to have behaviors from multiple, unrelated sources?

Interfaces solve this problem. A class can implement multiple interfaces. This allows a class to inherit different "contracts" or behaviors, a powerful form of multiple inheritance of type.

The diagram below visualizes these relationships. A class extends another class, an interface extends another interface, but a class implements an interface.

This diagram illustrates the core relationships in Java: a class can inherit from only one other class (extends), but it can implement multiple interfaces (implements). Interfaces themselves can also extend other interfaces.

The "Bro Code" channel has a creative and effective video explaining this with Prey and Predator interfaces. A Rabbit might only be prey, and a Hawk only a predator, but a Fish could be both.

Learn INTERFACES in 6 minutes! đŸ“‹

This video provides a fast-paced but clear example of why implementing multiple interfaces is so useful.

Watch the entire video. It's short and does a great job of showing how a Rabbit class implements Prey, a Hawk class implements Predator, and finally, how a Fish class can implement both Prey and Predator. This demonstrates the "multiple inheritance" capability of interfaces.

Let's recap what you saw in the video with a code snippet:

// Contract for things that can be hunted
interface Predator {
    void hunt();
}

// Contract for things that run away
interface Prey {
    void flee();
}

// This class implements BOTH contracts
class Fish implements Prey, Predator {

    @Override
    public void hunt() {
        System.out.println("This fish is hunting smaller fish");
    }

    @Override
    public void flee() {
        System.out.println("This fish is fleeing from a larger fish");
    }
}

// This class only implements one contract
class Rabbit implements Prey {
    @Override
    public void flee() {
        System.out.println("The rabbit is fleeing!");
    }
}

This ability to mix and match behaviors is fundamental to many design patterns, allowing you to create components that are both specialized and flexible.


Conclusion

In this lesson, we've established the critical role of interfaces in Java. They are the primary mechanism for defining abstract contracts that concrete classes can then implement.

Here are the key takeaways:

  • An interface is a blueprint or contract that defines a set of abstract methods and constants.
  • A class uses the implements keyword to agree to this contract and must provide a concrete implementation for all the interface's methods.
  • Interfaces allow for a form of multiple inheritance, as a single class can implement multiple interfaces, adopting several distinct contracts.
  • This mechanism is key to achieving abstraction, separating what a component does from how it does it.

You might be thinking, "This sounds a bit like what an abstract class does." You're right, there are similarities! However, they have distinct purposes and use cases. In our next lesson, we will dive into abstract classes, compare them directly with interfaces, and learn how to decide when to use each one. This will complete our foundational understanding of polymorphism in Java.