A generic interface in Java allows you to define an interface with type parameters, which can then be specified when the interface is implemented.
-
Promotes code reusability
-
Ensures type safety
-
Supports flexible interface contracts
Syntax
interface InterfaceName<T> {
T methodName(T param);
}
You can implement it with:
A generic class (using type parameters)
A non-generic class (fixing the type)
Code language: JavaScript (javascript)
Program-1 :Generic Interface with Non Generic class Implementation
interface Processor<T> { T process(T input); } class StringProcessor implements Processor<String> { @Override public String process(String input) { return input.toUpperCase(); } } public class Demo { public static void main(String[] args) { StringProcessor sp = new StringProcessor(); System.out.println(sp.process("lotusjavaprince")); } } /* LOTUSJAVAPRINCE */
Program 2: Generic Interface with Generic Class
interface Converter<T> { T convert(T value); } class IdentityConverter<T> implements Converter<T> { @Override public T convert(T value) { return value; } } public class GenericDemo { public static void main(String[] args) { Converter<Integer> intConverter = new IdentityConverter<>(); System.out.println("Converted: " + intConverter.convert(123)); } }*/
Program-3: Bounded Type in Generic Interface
interface Calculator<T extends Number> { double square(T value); } class DoubleCalculator implements Calculator<Double> { @Override public double square(Double value) { return value * value; } } public class BoundedDemo { public static void main(String[] args) { Calculator<Double> calc = new DoubleCalculator(); System.out.println("Square: " + calc.square(5.5)); } } /* Square: 30.25 */
Program-4
This program demonstrates the use of a generic interface (EmployeeProcessor) to process objects of a specific type (Employee) in a type-safe manner. It showcases how generics enable flexibility and reusability in processing different types of employees while ensuring compile-time type safety.
interface EmployeeProcessor<T> { void processEmployee(T emp); } class Employee { String name; Employee(String name) { this.name = name; } } class HRProcessor implements EmployeeProcessor<Employee> { @Override public void processEmployee(Employee emp) { System.out.println("Processed Employee: " + emp.name); } } public class EmployeeDemo { public static void main(String[] args) { Employee e = new Employee("Mahesh"); EmployeeProcessor<Employee> processor = new HRProcessor(); processor.processEmployee(e); } } /* Processed Employee: Mahesh */
Benfits
-
Generic interfaces define contracts using type parameters.
-
You can implement them in:
-
Generic classes (retain flexibility)
-
Non-generic classes (fix types)
-
-
Useful in collections, functional interfaces, and real-world systems.