Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

java

generics

What I mean is, in the code below:

class base {

}

class derived extends base {

}

class WTF {

    public void func(List<base> list) {

    }

    public void tryit() {
        func(new List<base>()); // ok
        func(new List<derived>()); // not ok
    }
}

But if the function simply took an object of base, it could take a derived object. Why is this?

like image 867
Rob Lourens Avatar asked Dec 02 '22 04:12

Rob Lourens


2 Answers

func needs to be defined as

public void func(List<? extends base> list) { ... }

This is because a List<derived> is not actually a List<base>, because a List<base> allows any kind of base in it, while a List<derived> 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.

like image 106
ColinD Avatar answered May 21 '23 09:05

ColinD


This is because if passing in a List<derived> 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<? extends base> 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.

like image 31
Luke Hutteman Avatar answered May 21 '23 08:05

Luke Hutteman