This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 507

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: 18545

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: 507

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
Similar Threads
Help me fix this-Part-2,so I can compile(generics doubt)
Collections and me...
Chapter 7 - Objective 6.3 & 6.4 - type parameter for method checkAnimals () method.
Help me fix this,so I can compile(generics doubt)