In our previous article, we discussed generics in Java. There are a few constraints that we can impose while working with Generics using extends
and super
keywords.
The ‘extends
’ keyword with respect to class
Let’s create the Demo<T>
class using extends
keyword.
class Demo<T extends Number> { T value; }
This implies that the class Demo will only accept Type arguments that extend the Number
class. That is the T can only be replaced by classes that extend the Number
class. So, while creating an instance for the class Demo, we should only use the classes that extend the Number
class.
Demo<Integer> d = new Demo<Integer>(); // valid Demo<Float> f = new Demo<Float>(); // valid
Since Float
and Integer
classes extend the Number
class they are valid to be specified as Type arguments. But, the below statement throws an error; as the String
class does not extend the Number
class.
Demo<String> s = new Demo<String>(); // this throws an error
The ‘extends
’ keyword with respect to methods
Let’s consider adding one more method to the Demo
class:
void show(ArrayList obj) { // -- Method code goes here }
This method says that it accepts the ArrayList
of Integers as its parameter. How can we modify it, so that it can only accept values that extend the Number
class?
This is how we do it:
void show(ArrayList<? extends Number> obj) {}
Now the ArrayList
here can accept values of all the Types that extend the Number
class. This is the syntax it;
The above method can also be written like this:
// T can be anything that will replace it void show(ArrayList<? extends T> obj) { // -- Method code goes here }
Usage of the ‘super
’ keyword
The same method discussed above can be modified to be written like this:
void show(ArrayList<? super Integer> obj) { // -- Method code goes here }
This means the ArrayList
will accept values of Type Integer
or of Type Number
, since Number
is the superclass to Integer
.
Let’s see a complete working example here;
After running the above program; the output will be;
Output:
15 [10, 10.2] [20, 20.2]
More topics will be discussed in upcoming articles.