Java Generic Interfaces
Declaring a Generic Interface
An interface can declare type parameters just like a class:
interface Converter<S, T> {
T convert(S source);
}
Converter<S, T> describes "something that turns an S into a T", without saying which types. Each implementation or use chooses them: a Converter<String, Integer> parses text into numbers; a Converter<Order, OrderDto> maps entities to API responses.
Generic interfaces are everywhere in the JDK, because interfaces define contracts and many contracts are independent of the data type:
| Interface | Contract |
|---|---|
Comparable<T> | "I can be compared with a T" |
Iterable<T>, Iterator<T> | "I can be looped over, producing Ts" |
Collection<E>, List<E>, Set<E>, Map<K, V> | Containers of elements |
Function<T, R>, Predicate<T>, Supplier<T>, Consumer<T> | Functional interfaces used by lambdas and streams |
Comparator<T> | "I can order Ts" |
Callable<V>, Future<V> | Tasks producing a V |
Implementing a Generic Interface
A class can implement a generic interface in two ways — fixing the type arguments, or staying generic and passing its own type parameters through. A generic interface can also contain default methods that use its type parameters.
import java.util.*;
public class I1 {
interface Converter<S, T> {
T convert(S source);
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> next) {
return s -> next.convert(convert(s));
}
}
static class CsvLineToList implements Converter<String, List<String>> {
@Override public List<String> convert(String line) {
List<String> out = new ArrayList<>();
for (String part : line.split(",")) out.add(part.strip());
return out;
}
}
interface Container<E> extends Iterable<E> {
void add(E item);
int size();
default boolean isEmpty() { return size() == 0; }
}
static class Bag<E> implements Container<E> {
private final List<E> items = new ArrayList<>();
@Override public void add(E item) { items.add(item); }
@Override public int size() { return items.size(); }
@Override public Iterator<E> iterator() { return items.iterator(); }
}
public static void main(String[] args) {
Converter<String, List<String>> splitter = new CsvLineToList();
System.out.println(splitter.convert("Asha, Chennai , 91"));
Converter<String, Integer> length = String::length;
Converter<String, String> trim = String::strip;
Converter<String, Integer> trimmedLength = trim.andThen(length);
System.out.println(trimmedLength.convert(" Java "));
Converter<String, Integer> fieldCount = splitter.andThen(List::size);
System.out.println("fields: " + fieldCount.convert("a,b,c,d"));
Container<String> tags = new Bag<>();
System.out.println("empty: " + tags.isEmpty());
tags.add("java");
tags.add("generics");
for (String t : tags) System.out.print("#" + t + " ");
System.out.println("(" + tags.size() + ")");
}
}
Output:
[Asha, Chennai, 91]
4
fields: 4
empty: true
#java #generics (2)
Fixing the type arguments
CsvLineToList implements Converter<String, List<String>> chooses concrete types, so its method is List<String> convert(String line) — the interface's S and T replaced by the chosen types. The class itself isn't generic.
Staying generic
Bag<E> implements Container<E> passes its own type parameter to the interface. Container<E> in turn extends Iterable<E>, so a Bag<String> can be used in a for-each loop, which produces Strings. Implementing iterator() by delegating to the internal list is all that's needed.
Lambdas and method references
Converter has a single abstract method, so it's a functional interface, and lambdas or method references can implement it. Converter<String, Integer> length = String::length creates an implementation on the spot: S = String, T = Integer.
Default methods that use the type parameters
isEmpty()inContaineris written once in terms ofsize()and works for every implementation.andThencombines two converters into one. It declares its own type parameterU(the final result type) and takes aConverter<? super T, ? extends U>: the next converter must accept what this one produces (? super T) and produce someU(? extends U) — the PECS rule from the Wildcards lesson.trim.andThen(length)is aConverter<String, Integer>that first strips and then measures (" Java "→"Java"→ 4).splitter.andThen(List::size)counts CSV fields.
This is exactly how Function.andThen and Comparator.thenComparing are built in the JDK.
A Class Can't Implement the Same Generic Interface Twice
public class Twice {
interface Handler<T> { void handle(T value); }
static class Both implements Handler<String>, Handler<Integer> {
public void handle(String s) { }
public void handle(Integer i) { }
}
}
Twice.java:3: error: repeated interface
static class Both implements Handler<String>, Handler<Integer> {
^
Twice.java:3: error: Handler cannot be inherited with different arguments: <java.lang.String> and <java.lang.Integer>
static class Both implements Handler<String>, Handler<Integer> {
^
2 errors
Because of type erasure, Handler<String> and Handler<Integer> are the same interface at runtime, with one handle(Object) method. A class can't implement it twice. The solution is composition: give the class two separate handler objects (fields or lambdas) instead of making it be both.
Implementing Comparable
Comparable<T> is the generic interface you'll implement most often. It gives a class a natural order, which Collections.sort, TreeMap, TreeSet, Collections.max and stream().sorted() use automatically.
import java.util.*;
public class Cmp {
record Version(int major, int minor, int patch) implements Comparable<Version> {
static Version parse(String text) {
String[] p = text.split("\\.");
return new Version(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]));
}
@Override public int compareTo(Version o) {
int c = Integer.compare(major, o.major);
if (c == 0) c = Integer.compare(minor, o.minor);
if (c == 0) c = Integer.compare(patch, o.patch);
return c;
}
@Override public String toString() { return major + "." + minor + "." + patch; }
}
public static void main(String[] args) {
List<Version> releases = new ArrayList<>();
for (String s : List.of("2.10.0", "2.9.3", "10.0.1", "2.10.1")) releases.add(Version.parse(s));
Collections.sort(releases);
System.out.println("sorted: " + releases);
System.out.println("latest: " + Collections.max(releases));
List<String> asText = new ArrayList<>(List.of("2.10.0", "2.9.3", "10.0.1"));
Collections.sort(asText);
System.out.println("sorted as strings: " + asText);
}
}
Output:
sorted: [2.9.3, 2.10.0, 2.10.1, 10.0.1]
latest: 10.0.1
sorted as strings: [10.0.1, 2.10.0, 2.9.3]
implements Comparable<Version>fixesT = Version, socompareToreceives aVersion— no casting of anObjectparameter, as was necessary before generics.- The comparison checks the major number first and moves to the next component only on a tie, giving the correct semantic-version order:
2.9.3 < 2.10.0 < 2.10.1 < 10.0.1. - Sorting the same versions as strings compares character by character, so
"10.0.1"comes first and"2.10.0"sorts before"2.9.3"— a common bug in software update checks. A proper type with a propercompareTofixes it. Integer.compareis used rather than subtraction (major - o.major), which can overflow for large values and return the wrong sign.
Practical Example: Composable Validators and a Result Type
Form and API input must be validated, and errors should be collected (so the user sees all problems at once) rather than thrown one by one. Two generic interfaces make a small, reusable validation library: Validator<T> checks a value of any type, and a sealed Result<T> represents either a valid value or a list of errors.
import java.util.*;
import java.util.function.*;
public class Valid {
sealed interface Result<T> permits Ok, Err {
static <T> Result<T> ok(T value) { return new Ok<>(value); }
static <T> Result<T> err(List<String> errors) { return new Err<>(List.copyOf(errors)); }
default <R> Result<R> map(Function<? super T, ? extends R> f) {
return switch (this) {
case Ok<T> ok -> ok(f.apply(ok.value()));
case Err<T> err -> err(err.errors());
};
}
}
record Ok<T>(T value) implements Result<T> { }
record Err<T>(List<String> errors) implements Result<T> { }
@FunctionalInterface
interface Validator<T> {
List<String> validate(T value);
static <T> Validator<T> of(Predicate<? super T> rule, String message) {
return v -> rule.test(v) ? List.of() : List.of(message);
}
default Validator<T> and(Validator<? super T> other) {
return v -> {
List<String> errors = new ArrayList<>(validate(v));
errors.addAll(other.validate(v));
return errors;
};
}
default <U> Validator<U> on(Function<? super U, ? extends T> field) {
return u -> validate(field.apply(u));
}
default Result<T> check(T value) {
List<String> errors = validate(value);
return errors.isEmpty() ? Result.ok(value) : Result.err(errors);
}
}
record SignUp(String email, String password, int age) { }
public static void main(String[] args) {
Validator<String> notBlank = Validator.of(s -> s != null && !s.isBlank(), "must not be blank");
Validator<String> emailFormat = Validator.of(s -> s != null && s.matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}"), "invalid email");
Validator<String> minLength10 = Validator.of(s -> s != null && s.length() >= 10, "password too short");
Validator<Integer> adult = Validator.of(a -> a >= 18, "must be 18 or older");
Validator<SignUp> signUp = notBlank.and(emailFormat).on(SignUp::email)
.and(minLength10.on(SignUp::password))
.and(adult.on(SignUp::age));
List<SignUp> requests = List.of(
new SignUp("asha@gocourse.in", "correct-horse-1", 27),
new SignUp("ravi@", "short", 16));
for (SignUp r : requests) {
Result<String> outcome = signUp.check(r).map(s -> "account created for " + s.email());
String text = switch (outcome) {
case Ok<String> ok -> "OK " + ok.value();
case Err<String> err -> "FAIL " + err.errors();
};
System.out.println(text);
}
Validator<Object> notNull = Validator.of(Objects::nonNull, "required");
System.out.println("generic validator reused: " + notBlank.and(notNull).validate(null));
}
}
Output:
OK account created for asha@gocourse.in
FAIL [invalid email, password too short, must be 18 or older]
generic validator reused: [must not be blank, required]
How the pieces fit:
Validator<T>is a generic functional interface: one abstract method,validate, returning the list of error messages for aT(empty if valid). Any lambda fromTtoList<String>is a validator.Validator.of(rule, message)is a static generic factory that builds a validator from aPredicate<? super T>. The? super Tallows general predicates, such asObjects::nonNullonObject.andcombines two validators and collects the errors from both. Its parameter isValidator<? super T>, so aValidator<String>can be combined with aValidator<Object>(notBlank.and(notNull)in the last line) — a validator for any object is also valid for strings.on(field)adapts a validator for a field into a validator for the whole object:minLength10.on(SignUp::password)turns aValidator<String>into aValidator<SignUp>by first extracting the password. Its type parameterUis the object type, inferred from the method referenceSignUp::password.- The combined
signUpvalidator checks all fields and reports every problem at once —ravi@fails three rules, all listed. Result<T>is a sealed generic interface with two generic record implementations.checkreturnsOk<T>orErr<T>. Its defaultmaptransforms the value inside anOk(here into a success message) while passing errors through unchanged. BecauseResultis sealed,switchover it with record patterns needs nodefaultbranch — the compiler knowsOkandErrare the only possibilities.
Libraries such as Jakarta Bean Validation (@NotBlank, @Email) and functional libraries (Vavr's Validation, Either) are built on the same ideas; writing a small version shows how generic interfaces, default methods and wildcards combine to make small pieces reusable for any type.