Skip to content

Intermediate · Inheritance, polymorphism and interfaces · topic 24 of 60 · 30 min

Interfaces

Explanation

An interface is a contract: a set of method signatures that implementing classes promise to provide. A class can implement many interfaces. Interfaces can also have default methods (with bodies), static methods and constants. Programming to interfaces, as in List<String> list = new ArrayList<>(), keeps code flexible. Sealed types (Java 17) limit which classes may implement them.

Why interfaces?

Many unrelated classes may share one ability: an Invoice, a Report and a Ticket can all be exported as PDF; a Car and a Fan can both be switched on. They have no common parent, and Java allows only one superclass. An interface describes an ability (a contract) that any class can sign up to, in addition to its own class hierarchy.

java
public interface Exportable {
    byte[] toPdf();                           // abstract by default (public abstract)
    default String fileName() {               // default method (Java 8+): has a body
        return getClass().getSimpleName().toLowerCase() + ".pdf";
    }
    static boolean isPdf(String name) {       // static helper on the interface
        return name.endsWith(".pdf");
    }
}

public class Invoice implements Exportable, Comparable<Invoice> {
    private final double total;
    public Invoice(double total) { this.total = total; }
    @Override public byte[] toPdf() { return ("Invoice " + total).getBytes(); }
    @Override public int compareTo(Invoice o) { return Double.compare(total, o.total); }
}

Rules and features

  • Interface methods without a body are implicitly public abstract; a class implementing the interface must implement them all (or be abstract).
  • Fields in interfaces are implicitly public static final constants.
  • A class can implement many interfaces: class Invoice implements Exportable, Comparable<Invoice>.
  • An interface can extend other interfaces.
  • default methods (Java 8) let interfaces add new methods without breaking existing implementations; private methods (Java 9) help share code between defaults.

Functional interfaces

An interface with exactly one abstract method is a functional interface, and you can implement it with a lambda (module 8). Comparator, Runnable and Predicate are examples. Mark your own with @FunctionalInterface so the compiler checks it.

java
@FunctionalInterface
interface DiscountRule { double apply(double price); }

DiscountRule festival = price -> price * 0.9;     // a lambda implements the single method
System.out.println(festival.apply(1000));          // 900.0

Abstract class versus interface

Abstract classInterface
How many can a class use?Extend ONEImplement MANY
Instance fields (state)YesNo (only constants)
ConstructorsYesNo
Method bodiesYesdefault, static and private methods
Best forA family sharing state and codeAn ability or contract many classes can have

Programming to an interface

java
java.util.List<String> names = new java.util.ArrayList<>();   // variable typed by the interface
// later, switching to LinkedList means changing ONE line:
// java.util.List<String> names = new java.util.LinkedList<>();
Code that depends only on List works with any List implementation.

Sealed interfaces (Java 17)

A sealed interface or class lists exactly which classes may implement or extend it: sealed interface Payment permits Upi, Card, Cod {}. The compiler then knows every possible case, so a switch over a Payment with case Upi u ->, case Card c -> and case Cod d -> needs no default (pattern matching for switch, Java 21). Each permitted class must be final, sealed or non-sealed.

Careful: Two interfaces with the same default method cause a conflict: if A and B both define default String name(), a class implementing both must override name() itself (it may call A.super.name()). Otherwise it does not compile.
Think of it like this: An interface is like a driving licence category. Anyone, a cook, an engineer or a student, can hold a "light motor vehicle" licence; it says what they can do, not what they are. A person can hold several licences, but has only one set of parents.
Tip: In Spring Boot projects you will see interfaces everywhere: services and repositories are usually interfaces, and the framework supplies or wires the implementations. Getting comfortable with interfaces now pays off in module 11.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Interfaces · 1/6

Interfaces

In this lesson you will define contracts with interfaces.

Prefer a video by a teacher? Find free videos on “java interface default method functional interface sealed abstract class vs interface” on YouTube ↗

In real life: SMS providers behind an interface

An app sends OTPs through an SMS provider. The code depends only on an SmsSender interface. In tests, a FakeSmsSender records messages; in production, a class wrapping the real provider is used. Switching providers later means writing one new class.

java
interface SmsSender { void send(String phone, String text); }

class FakeSmsSender implements SmsSender {
    final java.util.List<String> sent = new java.util.ArrayList<>();
    public void send(String phone, String text) { sent.add(phone + ": " + text); }
}

class OtpService {
    private final SmsSender sms;
    OtpService(SmsSender sms) { this.sms = sms; }
    void sendOtp(String phone, String otp) { sms.send(phone, "Your OTP is " + otp); }
}

Practice (0/3 done)

Task 1 · Question

interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } } Why does Sq not compile?

Task 2 · Question

Which is allowed in an interface?

Task 3 · Practice

Define interface SmsSender { void send(String phone, String text); } and two implementations: ConsoleSmsSender (prints) and FakeSmsSender (stores messages in a list). Write OtpService that receives an SmsSender in its constructor. In main, use the fake to check that exactly one message was sent.

Quick quiz

Question 1

1.How many interfaces can a class implement?

Question 2

2.Fields declared in an interface are…

Question 3

3.What is a functional interface?

Question 4

4.What does sealed interface Payment permits Upi, Card {} do?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How many interfaces can a class implement?

Answer: Many

Multiple interface implementation is allowed.

Fields declared in an interface are…

Answer: public static final constants

Interface fields are implicitly constants.

What is a functional interface?

Answer: An interface with exactly one abstract method

It can be implemented by a lambda.

What does sealed interface Payment permits Upi, Card {} do?

Answer: Allows only Upi and Card to implement Payment

Sealed types restrict their implementations.

A class implements an interface but misses one member. What happens?Related

Answer: Compile error CS0535

Every interface member must be implemented.

From Interfaces: contracts for behaviour

Why can a when over a sealed type skip else?Related

Answer: The compiler knows every subtype and checks all are handled

Exhaustiveness is checked at compile time.

From Data, enum and sealed classes, and objects

What is a functional interface?Related

Answer: An interface with exactly one abstract method

Lambdas implement functional interfaces.

From Lambdas and functional interfaces

Can an interface function have a default body in Kotlin?Related

Answer: Yes

Interfaces can provide default implementations.

From Inheritance and interfaces

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Inheritance, polymorphism and interfaces” before its exam: Packages and access modifiers.
  2. Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.

← Previous: Abstract classes