Intermediate · Inheritance, polymorphism and interfaces · topic 24 of 60 · 30 min
Interfaces
Explanation
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.
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.
@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.0Abstract class versus interface
| Abstract class | Interface | |
|---|---|---|
| How many can a class use? | Extend ONE | Implement MANY |
| Instance fields (state) | Yes | No (only constants) |
| Constructors | Yes | No |
| Method bodies | Yes | default, static and private methods |
| Best for | A family sharing state and code | An ability or contract many classes can have |
Programming to an interface
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<>();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.
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
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.
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)
interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } } Why does Sq not compile?
Which is allowed in an interface?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Packages and access modifiersInheritance, polymorphism and interfaces · same module
- Overriding and polymorphismInheritance, polymorphism and interfaces · same module
- Interfaces: contracts for behaviourC# and .NET · Inheritance, interfaces and records
- Data, enum and sealed classes, and objectsKotlin and Android App Development · Classes, objects and collections
- Lambdas and functional interfacesLambdas, streams and files
- Inheritance and interfacesKotlin and Android App Development · Classes, objects and collections
Questions people ask about this
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.
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.
What is a functional interface?Related
Answer: An interface with exactly one abstract method
Lambdas implement functional interfaces.
Can an interface function have a default body in Kotlin?Related
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 more topic in “Inheritance, polymorphism and interfaces” before its exam: Packages and access modifiers.
- Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.