-1

Why this is not allowed?

error: incompatible types: List<TextBook> cannot be converted to List<Book>

process(textBooks);

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println(“OK”)


        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println(“OK”);
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
ThinkGeek
  • 4,749
  • 13
  • 44
  • 91

2 Answers2

2

You are trying to pass a List<TextBook> into a method whose signature expects a List<Book>. This fails at compile time, because if the Java compiler were to allow it, then your process() method might try to use the contents of the list in the wrong way. Instead, use this version of process():

public static void process(List<? extends Book> books) {}

Now you may pass in any instance of Book, or any subclass of Book.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Thanks, but what do you mean by "if the Java compiler were to allow it, then your process() method might try to use the contents of the list in the wrong way." Can you please give me an example? – ThinkGeek Feb 16 '20 at 14:43
  • 1
    @LokeshAgrawal At compile time, something called _type erasure_ happens. This means that you really end up passing a `List` to a `process()` method which expects the same. If the `process()` method were to start using the list thinking that it contains books, when in fact it contains text books, then you might get unwanted behavior. Sometimes not using generics properly would result in a runtime exception, e.g. for trying to access methods which don't even exist. That might not be the case here, but the compiler is still preventing you from doing this. – Tim Biegeleisen Feb 16 '20 at 14:50
0

This is not allowed because you started out with an arraylist of Textbook. However you passed it to process as a list of Book. The process function could add something which is not a textbook to the list. At this point your original list would not be an arraylist of Textbook.

PiRocks
  • 1,708
  • 2
  • 18
  • 29