GENERICS IN JAVA

BOUNDED TYPES

java-logo

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().

MyGeneric class

If we try to compile this class we get an error.

Errore

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.

Extends

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.

Classe di test

To conclude, let us look at the figure. T accepts all parametric values of the specified superclass or one of its subclasses.

Tipi Possibili

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.

Metodi generici

The example returns a double divided by two.

Metodo generico

Let’s go on to write the test class.

Classe di Test

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.

Costruttore generico

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.

Interface generica

Let’s look at the test class.

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.

Bounded Types

Instead of Number in the class definition we can use a compatible type such as a Double.

Double

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

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.