File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Generics:Wild cards with upper Bounds Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics:Wild cards with upper Bounds" Watch "Generics:Wild cards with upper Bounds" New topic

Generics:Wild cards with upper Bounds

Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 561

Hi Ranchers,
I have written a java program for testing Generics with Upper Bound.
Please see the below example.
i have a clarification.why doesnt the java api provide feasibility for "Adding Lists" other than null values.???

Please explain me...

When i ran the above code i got a compile time error

Help provided will be highly appreciated.
Please help me out.

When The Going Gets Tougher,The Tougher gets Going
Henry Wong

Joined: Sep 28, 2004
Posts: 20525

The reason you can't add anything other than nulls, is because Java don't know the type -- all it knows is that it is something that extends Animal. This is *not* a language issue. The designers of Java didn't arbitrarly decide to not allow anything to be added... think about it... if all you know is that it is a unknown type that extends Animal, how would you type check it, to safely add items?

Basically, you use these types of references so that you can have more broad code -- in this case, so that you can write code that can work with any type that extends Animal. If you can't stay within the restrictions, then you need to write more specific code, that work with specific types.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 561

Hi Henry,
Im extremely thankful for your awesome answer.Thanks once again.

Im understanding the concepts of generics now,Thanks once again.

Deepak Lal
I agree. Here's the link:
subject: Generics:Wild cards with upper Bounds
It's not a secret anymore!