本文介绍了Java:创建对象时,为什么右侧的界面不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();

LinkedList实现队列。不应该排队在右边的上面的语句和LinkedList左边?

LinkedList implements Queue. Shouldn't Queue be on the right side of the above statement and LinkedList the left?

推荐答案

在Java中,你可以分配一个值为相同类型或更一般类型的变量。在你的例子中, new LinkedList< TreeNode>()是一个值。因为 LinkedList 实现 队列,它比 Queue 。即A LinkedList 队列

In Java, you can assign a value to a variable of the same type or a more general type. In your example, new LinkedList<TreeNode>() is a value. Since LinkedList implements Queue, it's more specific than Queue. i.e. A LinkedList is a Queue.

例如,这三个都是有效的

For instance, all three of these are valid

Object o = new LinkedList<TreeNode>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
LinkedList<TreeNode> list = new LinkedList<TreeNode>();

但是你不能写任何这些,因为它们的分配不正确。

But you can't write any of these because they're incorrect assignment.

LinkedList<TreeNode> o = new Object();
LinkedList<TreeNode> queue = new Queue<TreeNode>();

该示例中的第二个也是无效的,因为Queue是一个接口,您不能实例化(新的)接口,因为它不是具体类型

P.S. the second one in that example is also invalid because Queue is an interface, and you can't instantiate (new) an interface because it's not a concrete type

这篇关于Java:创建对象时,为什么右侧的界面不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:30