Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 6 Generics and Collections

We’ve discussed the static generic methods. How about non-static generic methods? Hmm, well, there is almost no difference when it comes to non-static methods. Obviously, you need to create an instance of the class in which the non-static method is defined in order to use the non-static method.

Generics and Subtyping

Here is a pop quiz.

Question: Only one of the following assignments is correct and compiles without errors. Which one is it? (Note: List is an abstract class, ArrayList extends List; similarly, Number is an abstract class and Integer

extends Number).

1.List<Integer> intList = new List<Integer>();

2.List<Integer> intList = new ArrayList<Integer>();

3.List<Number> intList = new ArrayList<Integer>();

4.List<Integer> intList = new ArrayList<Number>();

Answer: Only the second assignment will compile without errors.

Why? Let's discuss each of the options.

1.You are trying to assign intList of List<Integer> type to an object of type List<Integer>. But List is an abstract class. You cannot instantiate an abstract class, so you get a compiler error.

2.You are trying to assign intList of List<Integer> type with an object of type ArrayList<Integer>. Since ArrayList extends List, this is valid assignment and you don't get a compiler error.

3.You are trying to assign intList of List<Number> type with an object of type ArrayList<Integer>. ArrayList extends List—that is okay—but the generic parameter should be of the same type in the declaration as well as the initialization. So, you'll get a compiler error (type mismatch).

4.Same reason as in option 3.

You can assign a derived type object to its base type reference; this is what you mean by subtyping. However, for generics, the type parameters should match exactly—otherwise you’ll get a compiler error. In other words, subtyping does not work for generic parameters. Yes, this is a difficult rule to remember, so let’s discuss in more detail why subtyping doesn’t work for generic type parameters.

For class types, subtyping works. You can assign a derived type object to its base type reference. For generic type parameters, however, subtyping does not work. You cannot assign a derived generic type parameter to a base type parameter.

162

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]