Home >Java >javaTutorial >How Can I Combine Class and Interface Constraints Using Java Generics?
Java Generics with Class and Interface Compatibility
In Java, creating a class object with specific constraints can be challenging. A common scenario is defining a class object that extends a particular class while simultaneously implementing a specific interface. However, achieving both constraints simultaneously using generics has been a common point of contention.
Attempts to force a class to extend ClassA and implement interface InterfaceB using the syntax:
Class<? extends ClassA>
or
Class<? extends InterfaceB>
will only satisfy one requirement and fail to combine both.
Solution
Fortunately, Java generics allow for multiple interfaces or class plus interfaces. To achieve this, modify the wildcard declaration as follows:
<T extends ClassA & InterfaceB>
As illustrated in the Generics Tutorial by Sun, by appending & InterfaceName for each additional required interface, an arbitrarily complex combination can be achieved. For example, the JavaDoc declaration of Collections#max demonstrates this complexity:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
Preserving binary compatibility necessitates these intricate declarations.
Implementation with Class and Interface Constraints
To implement the desired restriction in a variable declaration, place a generic boundary on a class:
class classB { } interface interfaceC { } public class MyClass<T extends classB & interfaceC> { Class<T> variable; }
Conclusion
Java generics provide flexible ways to create constrained class and interface combinations. By understanding the syntax and limitations, developers can leverage this power to enforce specific requirements in their code.
The above is the detailed content of How Can I Combine Class and Interface Constraints Using Java Generics?. For more information, please follow other related articles on the PHP Chinese website!