问题
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