javagenericstype-conversiontypecasting-operator

How do i restrict some Generic class to only accept Integer ? not even take Double but only int values


{
    public static void main(String[] args)
    {
        G<Double> a=new G<Double>(10.9);
        
        G<String> b=new G<String>("hello");
        
        G c=new G("hell");
        
        System.out.println(a.getObject()); // print 10.9
        System.out.println(b.getObject());   // print hello
        System.out.println(c.getObject());  // print hell
        
       
    }
}

class G<Integer> {
    Integer obj;
    G(Integer obj)
    {
        this.obj=obj;
    }
    public Integer getObject()
    {
        return this.obj;
    }
}

in above code what is the use of make G class as Integer type only if its accepting everytype in main method ? How do i achieve That G class only takes Integer values , and don't convert in Double if i put double value but only take integers .


Solution

  • Like this. As was stated don't use generics. Just make your constructor accept just an Integer type. If you add a setter, accept only Integer types.

    class G {
        Integer obj;
        G(Integer obj)
        {
            this.obj=obj;
        }
        public Integer getObject()
        {
            return this.obj;
        }
    }