Concept of generics

Java generics allows the creation of a class or a method that can be reused by different data types or objects. This reduces the need for the same implementation throughout the code.

Another advantage is that the error checks are performed during the compile time, removing the possibility of runtime errors.

The class or a method denoted by <T> is recognized as a generic, where T is a type of parameter. In order to differentiate types of parameters from ordinary classes, single, uppercase letters are used.

Unbounded type parameters

Let’s create a simple generic class which prints out the value that was previously set:

public class Demo<T> {
   private T value;

   public void setValue(T value) {
      this.value = value;
   }

   public void printValue() {
      System.out.println(value);
   }
}

We can instantiate this class with the following:

Demo<String> onlyString = new Demo<>;
Demo<Integer> onlyInteger = new Demo<>;

and set the values:

onlyString.setValue(“Hello”);
onlyInteger.setValue(1);

If we try to do something like this, we will get a compilation error:

onlyString.setValue(1);

Now we can print out the values for both data types, by calling the same method from our generic class:

onlyString.printValue();  // “Hello”
onlyInteger.printValue(); // 1

Bounded parameter types

What if we want to limit classes that can be instantiated from our generic class? This can be achieved with a super keyword for lower, and extends for upper bounds.

Imagine having a hierarchy of classes:

public class Animal { }
public class Bird extends Animal { }
public class Eagle extends Bird { }

To create a generic class with bounded parameters we can do one of the following:

<T extends Animal> any class that is extended from the Animal, i.e Bird and Eagle

<T super Bird>superclasses of the Bird, i.e Animal, Object


“JAVA Generics” Tech Bite was brought to you by Nizam Alešević, Junior Software Engineer at Atlantbh.

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

Leave a Reply