Generics in Java

In this tutorial, we will learn about Generics in Java. Generics in Java can be compared to templates in C++.  It allow data types to act as a parameter to classes and methods. Data types such as Integer, String, … etc and user-defined types can act as parameters.

Generic is one of the important features of Java introduced by JDK5.

Java collection classes. It is a general feature of most classes to take parameter of type object defined and return value as an object. Because of Generic, classes can now take any data type as its parameter and return the same. The data types may or may not be of the same kind.

Earlier, using the same data type as parameters was impossible. The only possibility was to add extra checks. But it was not easy to implement. Soon as new age programmers felt the need to use the collection of elements which is of same data type. It became necessary to bring out some additional features. With the introduction of Generics, it was possible to check parameters during compile time automatically. This saved a lot of effort and time.

Types of Generics:

1)Generic class

2)Generic functions

Generic Class in Java

SYNTAX to declare generic class:

BaseType <Type> obj = new BaseType <Type>()

class Test<U>
    {
    U obj;
    Test(U obj){
         this.obj = obj;
         }
    public U getObject() {
        return this.obj;
    }

    }

 

Generic Functions

We write generic functions to use different types of arguments.

class Test
    {
    static <U> void Display_Generic (U element)
        {
            System.out.printIn(element.getClass().getName() + "=" + element);
        }

        public static void main(string[] args)
        {
            Display_Generic("Hello World");
            Display_Generic(10244);
        }

    }

 

Limitations to the use of Generics in Java

  • Generics are incompatible with primitives in declarations.
  • It is not possible create an instance of U.
  • DO NOT use static field type.
  • Creation of generic exception class is not possible.

You may also refer:

Leave a Reply

Your email address will not be published. Required fields are marked *