0

I am trying to create a generic class with a method that accepts a generic parameter. Now in another class create a method that will accept an object of that generic class. and call the generic method from new/main class. like below sample code.

public class MainClass {

    public static void main(String[] args) {
        MainClass gp = new MainClass();
        Class1<Integer> cls1=new Class1<>();
        gp.method1(cls1);
    }
    
    public void method1(Class1<? extends Number> obj2) {
        obj2.method(10);  //CT error - can't pass integer
    }
}

class Class1<T> {
    public void method(T arg) {
        
    }
}

I am getting compile time error. I am learning generic. I don't know where I am missing?

Randhir
  • 324
  • 3
  • 10
  • And ... what do you want to know? – El Hoss Jan 13 '22 at 19:04
  • @ElHoss I am getting Compile Time error. – Randhir Jan 13 '22 at 19:06
  • `? extends Number` could be `Float`. You can't just pass in an Integer. `? super Number` would work though. – shmosel Jan 13 '22 at 19:07
  • obj2 is a an object of any class parameterized with any class that extends Number. It can by Double, Integer, BigDecimal etc. So the error is ok - Integer may not fit. – Piotr Gwiazda Jan 13 '22 at 19:07
  • Go through this [Oracle Java Tutorial on Generics](https://docs.oracle.com/javase/tutorial/extra/generics/index.html) first. Then, come back here and refine your question with specifics or simply close the question. – hfontanez Jan 13 '22 at 19:07
  • @user16320675 Just research _Java PECS_. – hfontanez Jan 13 '22 at 19:11
  • @user16320675 so that you could answer your own observation. – hfontanez Jan 13 '22 at 19:12
  • @user16320675 Never mind. This questions is closed now for the same reason why I told you to research PECS. – hfontanez Jan 13 '22 at 19:13
  • It's not clear what you're trying to do. If you want your class to hold any Number, use `Class1`. If you want specifically Integers, why would you use `Class1 extends Number>`? – shmosel Jan 13 '22 at 19:15
  • @user16320675 no, I made the comment before I saw it was closed. Anyway, I thought you were bringing the point because of some confusion. I realize now that it was more rhetorical than anything else. Point taken. – hfontanez Jan 13 '22 at 19:21

0 Answers0