A java method that has a generic parameter- why can't I pass an object with a generic parameter that is a subclass of the method arguments?

"YOU AND THE ART OF ONLINE DATING" is the only product on the market that will take you step-by-step through the process of online dating, provide you with the resources to help ensure success. Get it now!

Up vote 2 down vote favorite share g+ share fb share tw.

What I mean is, in the code below: class base { } class derived extends base { } class WTF { public void func(List list) { } public void tryit() { func(new List()); // ok func(new List()); // not ok } } But if the function simply took an object of base, it could take a derived object. Why is this? Java generics link|improve this question asked Oct 27 '10 at 17:19Rob Lourens1,318319 89% accept rate.

Func needs to be defined as public void func(List list) { ... } This is because a List is not actually a List, because a List allows any kind of base in it, while a List only allows derived and its subclasses. Using? Extends base ensures that you can't add anything but null to the List, since you're not sure what subclasses of base the list might allow.

As an aside, you should try to follow standard Java naming conventions... classes starting with lowercase letters look strange, like they're primitives.

This is because if passing in a List was allowed, func() would be able to add base-typed elements to the list, thus invalidating the generic contract of the list (which should only allow for derived-typed contents) if on the other hand you define func as public void func(List list) you can still retrieve base-typed elements from list, but just won't be able to add any new elements to it, which is exactly the behavior you want.

To explain this behaviour of java, look at this example void addItem(List list) { list. Add(new Base()); } List l1 = new ArrayList(); addItem(l1); Base be = l1. Get(0); List l2 = new ArrayList(); addItem(l2); Derived d = l2.

Get(0); // Would cause runtime exception. That's why this code will not compile in the first place.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions