Generics in Java

  • Eclipse: Oxygen
  • Java: 1.8

Generics is a facility of generic programming that was added to Java in 2004 within version J2SE 5.0. It allows a type or method to operate on objects of various types while providing security of compile-time type.

Advantages

  • Reusability (You can compose a class or an interface once and use them for any type)
  • Stronger type checking, better type safety (reduces run time error)
  • Eliminate type casting statements (improve the program’s performance)

Getting started with generics

The generic allows us to define a single declaration for all the datatypes (not primitive) but all the Object such as Integers, String etc. Therefore, there is no need to define the same method for each data type, which is also time and code redundant technique. This also provides compile-time safety.

A generic type is a class or interface that is parameterized on types. Here we use angle brackets (<>) to specify the type parameter.

In the following program, we demonstrate the typecasting is not required while using generics class.

We have created a Generic class based on a property of T type (It means we are not sure about the type of object but it will be of some type). Inside the generics class, we have parameterized the Type of the generic class and also specified the data which would be passed to the constructor of the class.

GenericClass<String> genericData = new GenericClass<String>(“Some data”);

Output

Some data

Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time).

While another benefit of generics is that generics make an error to appear compile time than at run time.

In the following example, if the user provides an integer as input instead of String, generics throws compile time error.

Output

Compile time error: The constructor GenericClass<String>(int) is undefined.

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu