×

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea that lets users to dynamically select the reference type that a function or class function Object() { [native code] } takes.

Java Generics is a group of related types or a group of related methods. Integer, String, and even user-defined types may be provided as parameters to classes, methods, and interfaces thanks to generics. Usually, classes like HashSet or HashMap utilize generics.

Making a class generic provides it type-safe, ensuring it can function with any datatype. Let's look at an example to help us understand generics.

In the following Java example we are defining a class named Employee whose constructor (parameterized) accepts an Integer object. While instantiating this class you can pass an integer object

class Employee{
   Integer id;
   Employee(Integer id){
      this.id = id;
   }
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class ExampleofGenerics {
   public static void main(String args[]) {
      Employee std = new Employee(1432);
      std.display();
   }
}

Output:

Why are generics used in Java

A compile time exception results when passing any other object to the function Object() of this class.

public static void main(String args[]) {
   Employee std = new Employee("25");
   std.display();
}

Compile time errorCompile

ExampleofGenerics.java:12: error: incompatible types: String cannot be converted to Integer
   Employee std = new Employee("1432");
                              ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Employee ids can be supplied as (an object of) String values, Float values, Double values, etc. You must modify the function Object() if you wish to provide a value from another object.

class Employee{
   String id;
   Employee(String id){
      this.id = id;
   }
}
Or,
class Employee{
   Float id;
   Employee(Float id){
      this.id = id;
   }
}

They are referred to as parameterized types when you specify generic types since they may interact with any datatype. Generics do not support the usage of basic datatypes.

Creating generic types

To use generic parameter T or, GT as the basis for a generic type class

class Employee <T>{
   T obj;
}

Where T (generic argument) stands for the datatype of the object you can supply to the function Object() of this class. During the compilation process, this will be decided.

You can or should select the type of the generic argument as when instantiating the class.

Employee<Float> obj = new Employee<Float>();

We may use generics to rephrase the above example as:

GenericsExample.java

class Employee<T>{
   T id;
   Employee(T id){
      this.id = id;
   }
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Employee<Float> std = new Employee<Float>(1432.5f);
      std.display();
   }
}

Output

Why are generics used in Java

Now, while creating an instance of the Employee class, you may supply a parameter specifying the type of object you want.

GenericsExample.java

class Employee<T>{
   T id;
   Employee(T id){
      this.id = id;
}
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Employee<Float> ep1 = new Employee<Float>(1432.5f);
      ep1.display();
      Employee<String> ep2 = new Employee<String>("1432");
      ep2.display();
      Employee<Integer> ep3 = new Employee<Integer>(1432);
      ep3.display();
   }
}

Output

Why are generics used in Java

Why are generics necessary?

The following benefits come from using generics in your code:

  • When you utilise types (ordinary objects), it normally results in an error at runtime if you supply the wrong object as a parameter. Type checking at build time prevents this from occuring.
  • While using generics, the problem will occur during compilation and is simple to fix.
  • Code reuse: By utilising generic types, you may define a method, class, or interface once and use it several times with different arguments.
  • You must cast the object and utilise it for a number of formal kinds. The majority of the time, generics allow you to provide an object of the needed type directly without the need for casting.
  • Generic classes allow you to create a variety of generic algorithms

Java Generics Types

Generic method: Generic Java methods accept an argument and execute an operation before returning some result. It functions precisely like a regular function, except generic methods have type arguments that are listed according to the actual type. This enables a broader use of the generic technique. Because the compiler handles type safety, programmers may write code more quickly because they are not required to do time-consuming, individual type casts.

Generic classes: A generic class has the exact same implementation as a non-generic class. The presence of a type parameter section is the only variation. There may be different parameter types, each separated by a comma. Parameterized classes or parameterized types are classes that take one or more parameters.


Related Topics

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.