Java多态性混乱 [英] Java polymorphism confusion

查看:133
本文介绍了Java多态性混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问题来自Kathy Sierra和Bert Bates的Java SCJP5一书。
给定一个声明为的方法:

The question below is from Java SCJP5 book by Kathy Sierra and Bert Bates. Given a method declared as:

public static <E extends Number> List<E> process(List<E> nums)

程序员想要使用这样的方法:

A programmer wants to use the method like this:

// INSERT DECLARATIONS HERE
output = process(input);

可以在// INSERT DECLARATIONS这里放置哪一对声明以允许代码编译? (选择所有适用的选项。)

Which pair of declarations could be placed at // INSERT DECLARATIONS HERE to allow the code to compile? (Choose all that apply.)

A。

ArrayList<Integer> input = null;
ArrayList<Integer> output = null;

B。

ArrayList<Integer> input = null;
List<Integer> output = null;

C。

ArrayList<Integer> input = null;
List<Number> output = null;

D。

List<Number> input = null;
ArrayList<Integer> output = null;

E。

List<Number> input = null;
List<Number> output = null;

F。

List<Integer> input = null;
List<Integer> output = null;

G.以上都不是。

给出的正确答案是:B,E,F和书中的解释说明:

返回类型是肯定是声明为List,而不是ArrayList所以A,D是错误的。......

Correct Answers given are: B, E, F and the explanation in the book states:
"The return type is definitely declared as List, NOT ArrayList so A,D are wrong. ......"

这是我没有得到的...为什么它是返回类型必须只是List而不是ArrayList ??就像参数可以是ArrayList那么为什么cant返回类型也是arrayList?

This is what I don't get...why it is that the return type MUST be List only and not ArrayList?? Just like the argument can be ArrayList then why cant return type also be arrayList?

谢谢

推荐答案

这实际上不是特定于泛型,而是处理类型。

This is actually not specific to generics, but deals with types.

想到它的简单方法是, ArrayList 是一个列表,但列表不一定是 ArrayList

Easy way to think of it is, an ArrayList is a List, but an List is not necessarily an ArrayList.

ArrayList 实现 List 界面,因此可以将其视为列表。但是,仅仅因为某些东西实现 List ,它不是 ArrayList 。例如, LinkedList 实现 List ,但不是 ArrayList

ArrayList implements the List interface, so it can be treated as a List. However, just because something implements List, it is not an ArrayList. For example, LinkedList implements List, but is not an ArrayList.

例如,允许以下内容:

List arrayList = new ArrayList();
List linkedList = new LinkedList();

这是因为 ArrayList LinkedList 都实现 List 接口,因此它们都可以作为 List s。

This is because both ArrayList and LinkedList both implement the List interface, so they both can be handled as Lists.

但是,不允许以下情况:

However, the following is not allowed:

ArrayList arrayList = new LinkedList();

虽然 ArrayList LinkedList 实现 List ,它们不是同一个类。它们可能通过实现 List 的方法有相似之处,但它们是完全独立的类。

Although both ArrayList and LinkedList implement List, they are not the same class. They may have similarities by implementing the methods of List, but they are completely separate classes.

这篇关于Java多态性混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆