Bounded Generics doubts

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
jabenitez
Posts: 9
Joined: Tue Apr 17, 2018 5:03 am
Contact:

Bounded Generics doubts

Post 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.

admin
Site Admin
Posts: 10058
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Bounded Generics doubts

Post by admin »

If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 39 guests