Generic Interface In Java
In Java, a Generic Interface is an interface that uses type parameters, allowing it to work with any data type while maintaining type safety and reusability — just like generic classes.
It is especially useful when you want different implementations of an interface to handle different data types without repeating code.
🔹 Syntax of a Generic Interface
interface InterfaceName<T> {
T getValue();
void setValue(T value);
}
Here:
T is a type parameter.
You can replace
Twith any type (like String, Integer, Double, etc.) when implementing the interface.
🔹 Example 1: Basic Generic Interface
interface Container<T> {
void add(T item);
T get();
}
class StringContainer implements Container<String> {
private String value;
@Override
public void add(String item) {
this.value = item;
}
@Override
public String get() {
return value;
}
}
public class Main {
public static void main(String[] args) {
Container<String> stringBox = new StringContainer();
stringBox.add("Hello Generics Interface");
System.out.println(stringBox.get());
}
}
Output:
Hello Generics Interface
🔹 Example 2: Generic Interface Implemented with Different Types
class OrderedPair<K, V> implements Pair<K, V> {
private K key;
private V value;
public OrderedPair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public class Main {
public static void main(String[] args) {
Pair<String, Integer> pair = new OrderedPair<>("Age", 25);
System.out.println(pair.getKey() + ": " + pair.getValue());
}
}
Output:
Age: 25
📘 Real Example from Java
public interface Comparable<T> {
int compareTo(T o);
}
The Comparable
<T>interface is generic, allowing comparison of custom object types in a type-safe way.
