GENERICS IN JAVA
INTRODUCTION TO GENERICS
Generics are parametric classes, interfaces, and methods; said like that, it’s not like it’s immediately understandable. It will be in a while when we see the first generic class.
Classes, interfaces, and methods operate on parametric data types, conventionally specified through a letter T, or others that act as placeholders for any Data Type of Reference Type. Through Generics we are able to design much more flexible programs, let’s start right away with the code.
A GENERIC CLASS PART 1
Observe this class.
The private attribute is of type Object, and can accommodate both instances of Object and also any other class, since as you know all classes are derived from Object. Let’s look at the test class.
We have to cast as Object must be taken first to String then to int. We modify the program.
A GENERIC CLASS PART 2
What you see in the figure is a generic class.
With MyGeneric<T> we asserted that the class is a Generics. T represents a placeholder for any type, provided that it is not a primitive type. The placeholder T will be a Data Type specified in angle brackets by the user of the generic class. Let’s look at the test class.
In this second version we did not need to cast, and also no exceptions are caused at runtime. If we try to execute the operation shown in the figure we would get a compile error telling us that the type is incompatible. It is a compilation error and not a runtime exception, so definitely much better than before.
GENERAL FORM OF A GENERIC CLASS
Let’s look at the general syntax of a generic class.
We open angle brackets and provide one or more placeholders of parametric type. As mentioned, the parametric type is a placeholder for an actual Data Type, but it is specified from time to time when we go to instantiate the generic class.
type-arg-list we can avoid specifying it since the compiler is able to infer the correct types. arg-list is the list of parameters that will eventually be passed to the constructor if expected.
MULTIPLE TYPE PARAMETERS
Let’s look at a generic class with two parameters.
Let’s look at the test class that implements the generic class.
Always remember that parametric types must be reference types and not primitive types; the Boolean type we are passing is the Type Wrapper and not the primitive type. We could have also decided to pass the same Data Type, for example, two strings.
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