Java Generics Tutorial- Class, Functions of Generics in Java

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

1. Objective

In this Java Generics tutorial, we are going to study what is Java Generics and Java Generic Class with multiple parameters. Moreover, we will study the various advantages and Functions of generics in Java. At last, we will how to use generics in java with example.

So, let us start what is generics in Java with simple example.

Java Generics Tutorial- Class, Functions of Generics in Java

Java Generics Tutorial- Class, Functions of Generics in Java

2. What is Java Generics?

Generics in Java is like templates in C++. The thought is to permit write (Integer, String and so on and user-defined types) to be a parameter to techniques, classes, and interfaces. For instance, classes like HashSet, ArrayList, HashMap, and so forth utilize generics exceptionally well. We can utilize them for any kind.

Read about Decision Making in Java Programming with Syntax and Examples

a. What is Java Generic Class?

<> is used to specify parameter types in Java generic class creation.
The syntax for creating a Java generic class–

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

Note: In Parameter type, we cannot use primitives like ‘int’,’char’ or ‘double’.
Example –

class Test<T>
    {
// An object of type T is declared
        T obj;
        Test(T obj)
        {  this.obj = obj;  }  // constructor
        public T getObject()  { return this.obj; }
     }
class Main
  {
    public static void main (String[] args)
    {
        Test <Integer> iObj = new Test<Integer>(15);
        System.out.println(iObj.getObject());
        Test <String> sObj =
                          new Test<String>("DataFlair");
        System.out.println(sObj.getObject());
    }
}

b. Multiple type Parameters in Generic Classes in Java

class Test<T, U>
{
    T obj1;  // An object of type T
    U obj2;  // An object of type U
// constructor
    Test(T obj1, U obj2)
      {
         this.obj1 = obj1;
         this.obj2 = obj2;
     }
// To print objects of T and U
         public void print()
          {
              System.out.println(obj1);
              System.out.println(obj2);
         }
    }
class Main
    {
       public static void main (String[] args)
          {
              Test <String, Integer> obj =
              new Test<String, Integer>("GfG", 15);
              obj.print();
         }
   }

3. Java Generic Functions

We can also write generic functions in Java as they can be called by generic arguments which are handled by the compiler in Java.
Let’s Learn Polymorphism in Java with Example
Example –

class Test
  {
      static <T> void genericDisplay (T element)
         {
            System.out.println(element.getClass().getName() + " = " + element);
         }
      public static void main(String[] args)
           {
               genericDisplay(11);
               genericDisplay("datflair");
               genericDisplay(1.0);
          }
   }
Java Quiz

4. Advantages of Java Generics

Projects that utilizations Java Generics has numerous advantages over the non-generic code.

i. Code Reuse

We can compose a strategy/class/interface once and use for any kind we need.
Let’s discuss Interface in Java with Example program

ii. Sort Safety

Java Generics influence mistakes to seem to order time than at runtime (It’s constantly better to know issues in your code at an aggregate time as opposed to influencing your code to fall flat at run-time). Assume you need to make an ArrayList that store name of understudies and if by botch software engineer includes a whole number question as opposed to string, compiler permits it. However, when we recover this information from ArrayList, it causes issues at runtime.

import java.util.*;
class Test
 {
    public static void main(String[] args)
      {
// Creatinga an ArrayList without any type specified
        ArrayList al = new ArrayList();
        al.add("Sachin");
        al.add("Rahul");
        al.add(10);
        String s1 = (String)al.get(0);
        String s2 = (String)al.get(1);
        String s3 = (String)al.get(2);
     }
 }

iii. Individual Type Casting isn’t required

If we don’t utilize Java generics, at that point, in the above case each time we recover information from ArrayList, we need to typecast it. Typecasting at each recovery task is a major migraine. On the off chance that we definitely realize that our rundown just holds string information then we require not to pigeonhole it each time.

class Test
  {
     public static void main(String[] args)
       {
// Creating a an ArrayList with String specified
          ArrayList <String> al = new ArrayList<String> ();
          al.add("Sachin");
          al.add("Rahul");
// Typecasting is not needed
          String s1 = al.get(0);
          String s2 = al.get(1);
      }
 }

iv. Implementing nongeneric algorithms

By utilizing generics in Java, we can actualize calculations that work on various sorts of items and at a similar, they are type safe as well.
This was all in Java Generics Tutorial. Hope you like our explanation.

5. Conclusion

Hence, in this Java Generics Tutorial, we studied What is Generics in Java, Java Generics Class and How to use Java Generics with some Advantages & Functions in Generics in Java. In conclusion, we discussed some Java Generics Examples. Furthermore, if you have any query feel free to ask in the comment section.

Related Topic- Java Packages

For reference

1 Response

  1. chris says:

    can you exaplain all the keywords used along with the java default class name like ?

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.