Last active
April 8, 2023 09:18
-
-
Save pavly-gerges/2fe95035aab7f116e868fb01a2f1305e to your computer and use it in GitHub Desktop.
Generics in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Wrapper { | |
private Object object; | |
public Wrapper(Object object) { | |
this.object = object; | |
} | |
public void setObject(Object object) { | |
this.object = object; | |
} | |
public Object getObject() { | |
return object; | |
} | |
} |
API Design Tips
When designing your API, you should be aware of the following rules:
For class type generics and generic method type parameters:
- Lower bounds are not allowed.
- Instantiation of a variable of this type isn't allowed.
- Returning a parameterized type object will restrict the implementation to utilize generics and thus won't be backward compatible.
For wildcard generics:
- Upper bounds are used to define the type for the method returning values.
- Lower bounds give the developer the flexibility to use the abstraction over the l-value.
Last, but not least, in order to decide the best type of boundaries to use, think of the final type-erasure you want to have on your API:
- Declare the type-erasure you want to finally reach.
- Consider optimizing your code using Type-Generics.
Here is a nice tip from the Java tutorials:
In general, if you have an API that only uses a type parameter T as an argument, its uses should take advantage of lower bounded wildcards (? super T). Conversely, if the API only returns T, you'll give your clients more flexibility by using upper bounded wildcards (? extends T).
Resources
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Upper Bounded Wildcards V.S. Lower Bounded Wildcards
The (?) is called the wildcard operator, it provides the compiler with the ability to capture type compatibilities and replace them at compile-time.
The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
Upper bounded wildcard:
Lower bounded wildcard: