Can generic class implement an interface?
Yes, a generic class in Java can implement an interface. This allows the generic class to provide implementations for the methods declared in the interface while retaining the flexibility of working with different data types.
Table of Contents
Explanation
1. Interface Implementation
Implementing an interface in a generic class means that the generic class must provide concrete implementations for all the methods declared in the interface.
2. Type Parameters
When implementing an interface, the generic class can choose to use its own type parameter(s) or inherit type parameter(s) from the interface, depending on the design requirements,
3. Type Safety
Implementing an interface with a generic class allows for type-safe operations, ensuring that the methods declared in the interface operate correctly with the specified types.
java
// Example interface with a single method
interface Printable<T> {
void print(T value);
}
// Generic class implementing the Printable interface
class Printer<T> implements Printable<T> {
@Override
public void print(T value) {
System.out.println("Printing: " + value);
}
}
public class GenericClassInterfaceExample {
public static void main(String[] args) {
// Create an instance of the Printer class with String type parameter
Printer<String> stringPrinter = new Printer<>();
stringPrinter.print("Hello, World!");
// Create an instance of the Printer class with Integer type parameter
Printer<Integer> integerPrinter = new Printer<>();
integerPrinter.print(42);
}
}
In this Example,
The Printable interface declares a single generic class implement method print(T value) that accepts a value of type T. The Printer class implements this interface and provides a concrete implementation for the print() method. The type parameter T is used in both the interface and the implementing class to ensure type safety. The main() method demonstrates how instances of the Printer class can be created with different type parameters (String and Integer) and used to print values of those types. This example showcases how a generic class can implement an interface to achieve type-safe operations with different data types.