Generics Class Example

Generics Class Example

We can define our own classes with generics type. A class that can refer to any type object is known as generic class. Here, we are using T as a type parameter to create the generic class of specific type.
A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter in generics.

Need of Generic class

package com.example.generics;

public class GenericClassRequired {
    private Object t;

    public Object get() {
        return t;
    }

    public void set(Object t) {
        this.t = t;
    }

    public static void main(String args[]) {
        GenericClassRequired type = new GenericClassRequired();
        type.set("Mindclues");
        String str = (String) type.get(); // type casting, error prone and can cause                                                           //ClassCastException
        System.out.println(str);
    }
}

Here we notice that while using this class, we have to use type casting. If we didn't use, it can produce ClassCastException at runtime. Now we will use java generic class to rewrite the same class as shown below.

package com.example.generics;

public class GenericClassExample<T> {
    public T t;

    public T getT() {
        return this.t;
    }

    public T setT(T t1) {
        return this.t = t1;
    }

    public static void main(String args[]) {
        
        GenericClassExample<String> type = new GenericClassExample<String>();
        type.setT("Mindclues");
        
        GenericClassExample type1 = new GenericClassExample();
        type1.setT("MindAdmin");
        System.out.println(type1.getT());
        type1.setT(1);
        System.out.println(type1.getT());

    }
}

Related Articles

post a comment