OCP exam prep: functional interfaces¶
☕ Java 17 · 🎓 OCP 1Z0-829 · The One-Method Contract Behind Every Lambda
Optional page
This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.
Exam objective: Use lambda expressions implementing functional interfaces.
Four traps to watch for¶
Trap 1 — Count inherited abstract methods
An empty interface extending a functional one is functional. Add one abstract method in the child and it isn't anymore.
Trap 2 — default, static and private never count
They all have bodies. An interface with only these has zero abstract methods: not functional.
Trap 3 — The annotation is optional
@FunctionalInterface doesn't make an interface functional; it only triggers a compiler error when the rule is broken.
Trap 4 — Object signatures must match exactly
toString(), equals(Object) and hashCode() are free. equals(Movie) counts. int toString(); doesn't compile.
Practice questions¶
1. Which are functional interfaces? (Choose all that apply.)
interface Watchable { void watch(Movie m); }
interface Downloadable extends Watchable { }
interface Shareable extends Watchable { void share(User u); }
interface Ratable { default int stars() { return 5; } }
A. Watchable
B. Downloadable
C. Shareable
D. Ratable
Answer
A and B. Downloadable inherits watch(): one abstract method. Shareable has two. Ratable has zero: a default method never counts.
2. What happens when you compile this code?
1: @FunctionalInterface
2: interface SubscriptionCheck {
3: boolean isActive(Subscription s);
4: static SubscriptionCheck always() { return s -> true; }
5: default boolean isExpired(Subscription s) { return !isActive(s); }
6: }
A. It compiles
B. Error on line 1
C. Error on line 4
D. Error on line 5
Answer
A. Only isActive() is abstract. The static and default methods have bodies, so the annotation's check passes.
3. How many methods of EpisodeSorter count toward the single abstract method rule?
interface EpisodeSorter {
int compare(Episode a, Episode b);
boolean equals(Object other);
String toString();
boolean equals(EpisodeSorter other);
}
A. 1
B. 2
C. 3
D. 4
Answer
B. compare() and equals(EpisodeSorter). equals(Object) and toString() match Object's public methods exactly and are free. So EpisodeSorter is not functional.