Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to store any type of variable in class and get it using generics.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to store any type of variable in class and get it using generics.

Objective

Write a Java program to create a Generic Class that can store and retrieve any type of variable.

Algorithm / Approach

  1. Create a class Test<T>.
  2. Declare a private variable x of type T.
  3. Provide a set(T a) method to assign a value to x.
  4. Provide a get() method that returns type T.
  5. In main, create instances of Test for Integer, Float, and String.
Test.java
class Test<T> {
 private T x;
 void set(T a) {
  x = a;
 }
 T get() {
 return x;
 }
}
class Demo {
 public static void main(String[] a)
 {
  Test<Integer> t1=new Test<Integer>();
  Test<Float> t2=new Test<Float>();
  Test<String> t3=new Test<String>();
  t1.set(5);
  t2.set(8.5f);
  t3.set("Alok");
  System.out.println(t1.get());
  System.out.println(t2.get());
  System.out.println(t3.get());
 }
}

Expected Output

5
8.5
Alok

Explanation of the Program

  • This is a classic example of a Generic Container class.
  • By using the type parameter &lt;T&gt;, the class becomes completely agnostic to the data it holds. The compiler dynamically replaces T with the actual Object type you specify during instantiation.
  • This provides strong Type Safety. If you create a Test&lt;Integer&gt;, the compiler will instantly throw an error if you try to pass a String to the set() method.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT