Use of "super" with "?" in Java [duplicate]
Asked Answered
A

3

5

I am trying to read and understand some Java code. Here it is:

protected LoadTarget<? super PopulationLoadContext> createTarget(PopulationLoadContext context) {
    return createTransactionalTargetGroup(RiskScoresTables.All_Tables);
}

What does the <? super PopulationLoadContext> mean?

Amazon answered 24/7, 2013 at 22:30 Comment(3)
docs.oracle.com/javase/tutorial/java/generics/subtyping.htmlShena
See https://mcmap.net/q/258544/-java-generics-super-keywordMellman
+1: for learning me something new :)Nestling
A
8

In Java, that is a lower-bounded wildcard in generics, which stands for PopulationLoadContext or any superclass of that class.

It could be a LoadTarget<PopulationLoadContext>, or it could be a LoadTarget<Object>, or anything in between (if in between classes exist).

Autocrat answered 24/7, 2013 at 22:31 Comment(1)
@RichardW An excellent resource -- that I already linked.Autocrat
D
1

What Is It?

As stated by rgettman it's a generic type LoadTarget with a type argument set to a lower-bounded wildcard.

What Does It Allow?

At runtime a LoadTarget variable can be substituted (set) with a value of same type where the type argument is PopulationLoadContext or an ancestor.

Why?

To allow flexibility - a family of different instantiated types can be substituted for one another and work fine. Within LoadTarget, the type parameter is used for method parameters (input) or for upper type bounds of internally instantiated generic types. In these cases a broader type is substitutable for the original type because it is more accommodating. The generic type is said to have contravariance with it's type parameter

Diverticulitis answered 24/7, 2013 at 22:50 Comment(0)
M
1

More generally (not just Java speaking), if you want to get a bigger picture, it is also called covariance / contravariance: http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29 see Java section:

"given a List<? extends Foo>, then an element can be retrieved and safely assigned to a Foo type (covariance). Given a List<? super Foo>, then a Foo object can be safely added as an element (contravariance)."

Mame answered 24/7, 2013 at 23:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.