Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics:Wild cards with upper Bounds

 
Deepak Lal
Ranch Hand
Posts: 561
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 21122
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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.

Henry
 
Deepak Lal
Ranch Hand
Posts: 561
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry,
Im extremely thankful for your awesome answer.Thanks once again.



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

--
Deepak Lal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic