java - Performing operation using Generic and primitive type not working -


trying learn basic operations using java-genric, tried make generic class, takes number , operation on , returns value throwing error

parent class :

public class helloworld{       public static void main(string []args){          mathsexec<integer> my_obj = new mathsexec<integer>();         int rst = my_obj.doaddition(100);         system.out.println("solution : "+rst);      } } 

generic class :

class mathsexec<t>{ //didn't extend number because m strictly sending int values       t doaddition(t nmbr){         int k=100;         t rst;         rst = nmbr+k;         return rst;     } } 

error :

mathsexec.java:6: error: bad operand types binary operator '*'

    rst = nmbr+k;               ^   

first type: t
second type: int
t type-variable: t extends object declared in class mathsexec 1 error

i understand why error coming(incompatible types operation) per generics, type t should have been converted integer before doing + operation...or there other explanation should know????

p.s : please go easy, java not strong suite!!

generic types not known in compile time. therefore, compilation error. , makes sense, because there no guarantee * operator work on generic type t.

a trivial educational solution might adding interface called multipliable , adding abstract method multiply() it, calling method in doaddition method. btw need change class definition like

class mathsexec<t extends multipliable> 

additional clarifications:

  1. we have come understanding cannot use operators * classes, primitive types only.

  2. if have use generics , have operations on generic types, have keep compiler happy , assure that generic object, have method. , through t extends someclass.

  3. if want practice generics without using interfaces or abstract classes or whatever, common use case custom data structures. possible not need many operations on data storing. put them in structure.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -