With Java Generics, we name Java Formal Type Parameter T, E, K, and V conventionally. If an instance of a Format Type Parameter, what available methods we can invoke on them?
Java Formal Type Parameter is Object
Formal Type Parameters without bounds represent the Object class, and they have the same set of methods. Consider the following codes. We have a generic class Box2 with T Formal Type Parameter. During coding or compile-time, we can only see methods from the Object class. In the post three ways to implement a Generic Interface, when we ignore or remove the Formal Type parameter, we get an Object class.
From this perspective, we can appreciate the use of bounds in generics, especially with upper limits.
Object Methods We Invoke
If we list all the Object class methods through an IDE, we can see the same list of methods.
Java Formal Type Parameter With Upper Bound
When we want our Java Format Type Parameter to have an upper bound, we use the extends keyword within the angle brackets. Consider the following codes. Now, the itemInBox property has the getItemName() and setItemName() methods from the Item class.
Java Formal Type Parameter With Lower Bound
The Formal Type Parameter with lower bound is a bit different. We cannot use it to create generics classes with lower bounds. Most of the time, we use formal type parameters with lower bounds when we are working with collections. We will talk more about this on later posts.
For more information, please visit Java Generics.
This post is (now) part of a reboot Java tutorial.