0

I am new to generics. If I have already created a generic interface IList. But I want to create a method that only works on a list of Students(Student is also another class I created for that problem). Where should I put this method.

P.S. I tried to put this method inside IList class but that doesn't compile since the elements are T rather that Student. What should I do?

Wenyu
  • 1
  • It maybe what you need https://stackoverflow.com/questions/2081663/how-to-set-constraints-on-generic-types-in-java – Tran Ho Mar 08 '20 at 21:52
  • Does this answer your question? [How to set constraints on generic types in Java?](https://stackoverflow.com/questions/2081663/how-to-set-constraints-on-generic-types-in-java) – ktzr Mar 08 '20 at 22:09

1 Answers1

0

It is not possible to make 'conditional' methods, as in, it is not possible to make a method which only exists for some of the types. A Foo<T> object doesn't change what methods it has based on the T.

You can create a subtype:

public class Foo<T> {
    private List<T> elems = ...;
    void bar();
}

public class StudentFoo extends Foo<Student> {
    void baz() {
        for (Student s : elems) {}
    }
}

works fine. But that isn't going to magically give all Foo<Student> objects a baz method; you'd have to make them specifically as new StudentFoo(), not as new Foo<Student>().

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72