Java: When creating an object, why isn't the interface on the right hand side?

岁酱吖の 提交于 2019-12-11 18:49:23

问题


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

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


回答1:


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>();

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




回答2:


The example declares queue to be a reference to an object having the type of Queue<TreeNode>, but the variable must refer to an instance of a concrete implementation of that interface, LinkedList<TreeNode>. By coding to the interface, you agree to use only the methods of Queue. This allows you to change the implementation if required, without changing how queue is used.



来源:https://stackoverflow.com/questions/9552452/java-when-creating-an-object-why-isnt-the-interface-on-the-right-hand-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!