Java-Generics Only with Objects

Generics Only with Objects

When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. You cannot use a primitive type, such as int or char. For example, with GenClass, it is possible to pass any class type to T, but you cannot pass a primitive type to a type parameter. Therefore, the following declaration is illegal :

Generics Only with Objects

Of course, not being able to specify a primitive type is not a serious restriction because you can use the type wrappers to encapsulate a primitive type. Further, Java’s autoboxing and auto-unboxing mechanism makes the use of the type wrapper transparent.

Program

Generics Only with Objects

Generics Only with Objects

Program Source

class GenClass<T> {
    
    T ob;
    
    GenClass(T obj)
    {
        ob = obj;
    }
    
    T getOb()
    {
        return ob;
    }
    
    void showType()
    {
        System.out.println("T Type : "+ob.getClass().getName());
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        GenClass<int> iob = new GenClass<int>(50);
    }
}

Leave a Comment