GENERICS IN JAVA
BOUNDED TYPES
To understand how to implement the Bounded Type we start right away with an example. The attribute t in the figure is of type Object, as we have seen in previous lessons to turn it into a Type Wrapper we need to use the method intValue().
If we try to compile this class we get an error.
It is not recognized by the compiler because intValue() is a method of class Number and we are working with a type Object which is at a higher level, plus the square method is not a true generic method. Imagine if instead of an int we use a boolean. The problem is solved by a bounding of the allowed parametric types, this means using Bounded Types.
We are saying this with <T extends Number>. This is a generic class although generic to a certain extent. In fact, the parametric type T must either be of type Number or of a subclass of type Number. We write a test class for verification.
To conclude, let us look at the figure. T accepts all parametric values of the specified superclass or one of its subclasses.
GENERIC METHODS
You can declare a generic method in a non-generic class. Let us introduce the syntax. Before the return type, the list of parametric types that will later be included in the method parameters must be specified. Let’s look at an example to clarify the definition given in the figure.
The example returns a double divided by two.
Let’s go on to write the test class.
GENERIC CONSTRUCTOR
The constructors of a non generic class can also be made generic just as we have seen for methods. Let’s look at a generic constructor.
GENERIC INTERFACES
We immediately introduce a generic interface. If a class implements a generic interface, then the class will also have to be generic, have the same number of parametric types that then must be compatible with those of the interface.
Let’s look at the test class.
Let us look at an example with a Bounded Types. There is no need to repeat the Bounded Types after the implements keyword since the compiler can infer the correct Types.
Instead of Number in the class definition we can use a compatible type such as a Double.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON GITHUB
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CorsoJava.jar
- Or run the main found in the file CorsoJava.java.
Leave A Comment