In previous tutorial, we have seen how to use wild card character . Wild card character allows to pass any type of list as parameter to the method . Then, how to force the method to allow particular type list or it’s sub types list as parameter . The answer is using ‘extend’ keyword. Now also we can’t add any element to list except null . See , below example.

import java.util.ArrayList;
import java.util.List;

public class Sample {
    public int size(List<? extends String> arrayList) {
        arrayList.add("raj"); // compiler error. except 'null' , we can't add
                                // any type
        return arrayList.size();

    public static void main(String as[]) {
        List<String> names = new ArrayList<String>();
        List<Integer> age = new ArrayList<Integer>();
        System.out.println(new Sample().size(names));
        System.out.println(new Sample().size(age)); // causes compiler error
        // size method allows either String type or it's subtypes only

We can extend either class or interface. We can’t extend both at once . If we extend interface, then method allows implementation classes type list .