ComputersProgramming

Java Generics: Description and Methods

Since its inception, the Java language has undergone a lot of changes, which, undoubtedly, brought positive features to its functionality. One such significant change is the introduction of Java Generic or generalization. This functionality has made the language not only more flexible and versatile, but also much safer in terms of reducing data types.

The fact is that before the introduction of generics, the generic code in Java could be created, only with links of type Object. Such links can be assigned to any object. After all, all classes in Java are implicit descendants of the Object class. However, this approach is a potential source of many type safety errors when you explicitly convert an object from Object to the target type. When generalizations are used, all casts are performed implicitly and automatically, which excludes even the potential possibility of errors.

Java Generics: description and example

Let us examine a simple example of applying the generalization to the usual class in the figure below. And only then will we proceed to a detailed examination of all the subtleties and nuances of Java Generic.

Notice how the Pair class is declared. Right after the class name, the angle brackets are opened, in which the letter T is indicated. It is a kind of placeholder that will be replaced with a specific type when creating an instance of this class. It looks like this: Pair obj = new Pair (). It should be noted that instead of T, you can specify any letter, but, as a rule, use T, V or E.

Note: Starting with the eighth version of Java, specifying the target type when the link is declared, you can leave the angle brackets in the constructor empty. So the above example can be rewritten as follows: Pair obj = new Pair <> ().

When a class is declared this way, then in this body, instead of specific types of fields, references, and methods returned by methods, you can use this letter. Because T is replaced by a specific type when creating a class object, the first and second fields in this case will be of type Integer.

Following the logic, the arguments firstItem and secondItem, passed to the corresponding constructor, must also be of type Integer or its subclass. If you try to pass a data type that is different from what was specified when the object was created, the compiler will not skip this error. So, the constructor with arguments when creating the object will have the following form: Pair obj = new Pair <> (new Integer (1), new Integer (2)). The same applies to the arguments to the setFirst and setSecond methods. And as you probably already guessed, the getFirst and getSecond methods will return values of type Integer.

A generic class with several type parameters

In generic classes, you can also declare several type parameters that are specified in angle brackets, separated by commas. The Pair class for this case is presented in the figure below.

As you can see, when creating an instance of such a class, the same number of types as the parameters should be specified in the angle brackets. If you are familiar with such kind of data structure as Map, then you might notice that the same principle is used there. There, the first argument specifies the type of the key, and the second specifies the type of the value. It should be noted that the types of arguments passed to the object creation can be the same. So, the following declaration of an instance of the Pair class is absolutely correct: Pair obj.

Some features of generalizations

Before proceeding further, it should be noted that the Java compiler does not create any different versions of the Pair class. In fact, during the compilation process, all information about the generic type is deleted. Instead, the corresponding types are cast, creating a special version of the Pair class. However, the program itself still has a single generalized version of this class. This process is called in the Java Generic cleanup type.

Let's note an important point. Links to different versions of the same java generic class can not point to the same object. That is, let's say we have two links: Pair obj1 and Pair obj2. Therefore, an error occurs in the line obj1 = obj2. Although both variables are of type Pair , the objects they refer to are different. This is a vivid example of the security of types in Java Generic.

Restrictions imposed on generalized classes

It is important to know that generalizations can only be applied to reference types, that is, the argument passed to the generic class java argument must necessarily be the type of the class. Such simple types as, for example, double or long, can not be transmitted. In other words, the following line of Pair class declaration is not valid: Pair obj. However, this limitation is not a serious problem, since Java has a corresponding wrapper class for each primitive type. Strictly speaking, if you want to encapsulate an integer and a logical value in the Pair class, auto-pack will do everything for you: Pair obj = new Pair <> (25, true).

Another serious limitation is the impossibility of creating an instance of a type parameter. So, the following line will cause a compilation error: T first = new T (). This is obvious, since you do not know in advance whether a full class or an abstract interface will be passed as an argument. The same goes for creating arrays.

Limited types

Quite often there are situations when it is necessary to limit the list of types that can be passed as an argument to the java generic class. Let's assume that in our Pair class we want to encapsulate only numerical values for further mathematical operations on them. To do this, we need to set the upper bound of the type parameter. This is implemented using a superclass declaration inherited by all arguments passed in angle brackets. It will look like this: class Pair . In this way, the compiler learns that instead of the T parameter, you can substitute either the Number class or one of its subclasses.

This is a common technique. Such restrictions are often used to ensure compatibility of type parameters in the same class. Consider an example on our Pair class: class Pair . Here we tell the compiler that type T can be arbitrary, and type V must be either type T or one of its subclasses.

The restriction "from below" occurs in exactly the same way, but instead of the word extends, the word super is written. That is, the declaration of class Pair indicates that instead of T, either an ArrayList or any class or interface that it inherits can be substituted.

Generic Java Methods and Constructors

In Java generalizations can be applied not only with respect to classes, but also methods. So, the generalized method can be declared in the usual class.

As you can see in the figure above, there is nothing complicated in the declaration of the generalized method. It is enough to put angle brackets before the return type method and specify type parameters in them.

In the case of a constructor, everything is done in the same way:

Angle brackets in this case are placed before the name of the constructor, since it does not return any value. The result of the work of both programs will be:

Integer

String

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.delachieve.com. Theme powered by WordPress.