3

I am trying to understand what is the purpose of using <? super T> in generics in Java. I have read a lot, but haven't understood it yet. It is clearly for me using <T extends SomeClass>, if the class is SomeClass or subclass of SomeClass we don't need to now exact type of subclass, we know only that it has methods of superclass SomeClass, so we can invoke methods like T.someMethod(); It is very powerful feature. But I cannot understand purpose of using <T super SomeClass>.

What privileges we have writing such wildcard? T is super class of SomeClass, so what Super class may doesn't have methods of SomeClass, we can only ensure that super class of SomeClass has all methods of Object so this becomes useless, so what is the purpose of using this?

Patrick M
  • 10,547
  • 9
  • 68
  • 101

1 Answers1

2

You can express Lower Bound wildcard using ? super T. Let say that you want to develop a method that can put Double into a list .

public void foo(List<Double> d) {}

But if you can declare this method like

public void foo(List<? super Double> d) {}

Then you can pass List<Double>, List<Number>, and List<Object> . Hence you achieved more flexibility and re-usability. Also other way to look at ? super T is via PUT principle

use a super wildcard when you only put values into a structure.

sol4me
  • 15,233
  • 5
  • 34
  • 34
  • Thx for answer but List and List are not compatible. I cannot put Object in List . –  Sep 19 '14 at 05:35
  • Obviously that's why i mentioned "That you can pass" , i didn't mentioned that you can put – sol4me Sep 19 '14 at 05:36