简体   繁体   中英

Java generics extends and super implemented in collection and its subtypes

I want to understand a bit more on java generics covariance and contravariance and how extends and super together work wrt collection and individual objects

class P1 {}

class P2 implements Collection<P2> { // implement collection methods }

class Base<T> {
transient List<T> _instList = new ArrayList<>();

protected Base(final List<T> list) {
    _instList = list;
}
}

@SuppressWarnings("unchecked")
class Emp<T> extends Base<Object> {

public <C extends Collection<T>> Emp(final List<? super C> list) {
    super((List<Object>) list);
}

public <C extends Collection<T>> void salary(C c) {

}

public <C extends Collection<? super T>> void credit(C c) {

}
}

In Main method,

1 Emp<P1> emp1 = new Emp<>(new ArrayList<P1>());// works, compiles fine
2 Emp<P2> emp2 = new Emp<>(new ArrayList<P2>());// works, compiles fine
3 emp1.credit(new P1()); // doesn't compile
4 emp2.credit(new P2()); // works 

I want to understand how & why line 1 works when P1 is not a type of Collection

2 & 4 does compile, because P2 is a sub type of Collection.

Please clarify

Line 1 matches the typebound of the constructor.

class Emp<P1> extends Base<Object> {

    public <C extends Collection<P1>> Emp(final List<? super C> list) {
        super((List<Object>) list);
    }

replacing T with P1 and C is ArrayList. Nothing in that code requires P1 actually to implement Collection.

It is required to call credit(). Thats why you get an error in line3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM