Home >Java >javaTutorial >How Can I Combine Class and Interface Bounds in Java Generics?
Java Generics: Combining Class and Interface Bounds
In Java, generics offer the capability to define types that can operate on different types of objects. A common challenge arises when you want to create a class object that is restricted to extend a specific class while implementing a specific interface.
Let's consider a use case where we want to create a Class object that represents a class extending ClassA and implementing the InterfaceB interface.
Initially, you might attempt to use the following wildcards:
Class<? extends ClassA>
or
Class<? extends InterfaceB>
However, using either of these will not allow you to enforce both requirements simultaneously.
The key to achieving this is to use multiple bounds in your wildcard. The syntax for such a wildcard is:
<T extends Class & Interface>
Applying this to our scenario, we get:
Class<? extends ClassA & InterfaceB>
As explained in the Java Generics Tutorial, you can use multiple bounds to specify that a type parameter must extend a given class and implement one or more interfaces. The use of the & operator separates the bounds.
While this solution allows you to achieve your goal, it can become complex. For instance, consider the Collections#max method in Java, which has the following declaration:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
This sophisticated syntax ensures binary compatibility while enforcing specific type constraints.
In your use case, you can create a generic class with the desired bounds:
public class MyClass<T extends ClassA & InterfaceB> { Class<T> variable; }
This approach allows you to create a variable that has the desired restrictions, such as:
MyClass<ClassB>.variable
The above is the detailed content of How Can I Combine Class and Interface Bounds in Java Generics?. For more information, please follow other related articles on the PHP Chinese website!