Page 1 of 1

Bounded Generics doubts

Posted: Wed Apr 25, 2018 4:44 am
by jabenitez
Hi,

someone could explain to me how the unbounded works in generic types, please?

With the following class hierarchy:

Code: Select all

class A
class B extends A
class C extends C
I understood:

Code: Select all

? extends A --> it's allowed the following classes: A,B or C
? extends B --> it's allowed the following classes: B or C
? extends C --> it's allowed the following classes: C

Code: Select all

? super A --> it's allowed the following classes: A or Object
? super B --> it's allowed the following classes: B, A or Object
? super C --> it's allowed the following classes: C, B, A or Object
am I wrong with this above?


I have doubts with the following examples:

Code: Select all

static class Vehicle {}
static class Car extends Vehicle {}


List<? extends Vehicle> vehicless = new ArrayList<Vehicles>();
vehicless.add(new Car()); // if Car is superclass of Vehicle, why this statement does not compile?
vehicless.add(new Vehicle()); // why this statement does not compile?

Code: Select all

List<? super IOException> exceptions = new ArrayList<Exception>();
exceptions.add(new Exception()); // if Exception is superclass of IOException, why this statement does not compile?
exceptions.add(new IOException()); // it's correct because the IOExecption is included in super clause
exceptions.add(new FileNotFoundException()); // if FileNotFoundException is not included in super clause, why this statement is correct?

Thanks in advance.

Re: Bounded Generics doubts

Posted: Wed Apr 25, 2018 4:56 am
by admin