Generic Class Example in Java

In this post we are going to learn what is generic class with example. Generic class in java example. 

A Generic class means in that class we can use any type as parameter(T).  In this example we are using the T type parameter to create a generic class.


  Simple Example of Creating Generic Class in Java:

 


package com.java.Examples;

public class TestGeneric {
   public static void main(String[] args) {
      Car<String> name = new Car<String>();
      Car<Integer> speed = new Car<Integer>();

      name.add("XUV500");
      speed.add(200);


      System.out.printf("Name of the car is :%s\n", name.get());
      System.out.printf("Speed of the car is :%d\n", speed.get());
   }
}
//Creating Generic Class
class Car<T> {
   private T obj;

   public void add(T obj) {
      this.obj = obj;
   }

   public T get() {
      return obj;
   }   
}

Output:
Name of the car is : XUV500
Speed of the car is : 200



In the above example T type parameter indicates that it can refer to any type like String, Integer etc.


  Other Java Posts:

  You May Like:



No comments:

Post a Comment

If you have any doubts, please discuss here...👇