Generic Interfaces
Generic interfaces are specified like generic classes.
interface MinMax<T extends Comparable<T>> {
T max();
}
class MyClass<T extends Comparable<T>> implements MinMax<T> {
T[] vals;
MyClass(T[] o) {
vals = o;
}
public T max() {
T v = vals[0];
for (int i = 1; i < vals.length; i++) {
if (vals[i].compareTo(v) > 0) {
v = vals[i];
}
}
return v;
}
}
public class Main {
public static void main(String args[]) {
Integer inums[] = { 3, 6, 2, 8, 6 };
Character chs[] = { 'b', 'r', 'p', 'w' };
MyClass<Integer> a = new MyClass<Integer>(inums);
MyClass<Character> b = new MyClass<Character>(chs);
System.out.println(a.max());
System.out.println(b.max());
}
}
In general, if a class implements a generic interface, then that class must also be generic.
If a class implements a specific type of generic interface, such as shown here:
class MyClass implements MinMax<Integer> { // OK
then the implementing class does not need to be generic.
Here is the generalized syntax for a generic interface:
interface interface-name<type-param-list> { // ...
type-param-list is a comma-separated list of type parameters. When a generic interface is implemented, you must specify the type arguments, as shown here:
class class-name<type-param-list>
implements interface-name<type-arg-list> {
Home
Java Book
Language Basics
Java Book
Language Basics
Generics:
- Generic Class
- Generic Bounded Types
- Generic Wildcard Arguments
- Generic Bounded Wildcards
- Generic Method
- Generic Constructors
- Generic Interfaces
- Raw Types and Legacy Code
- Generic Class Hierarchies
- Run-Time Type Comparisons Within a Generic Hierarchy
- Overriding Methods in a Generic Class
- Generic Restrictions
- Generic Array Restrictions