interface作为Java中的方法参数 [英] interface as a method parameter in Java
问题描述
我几天前接受了一次采访,并抛出了这样的问题。
I had an interview days ago and was thrown a question like this.
问:反转链表。下面的代码给出:
Q: Reverse a linked list. Following code is given:
public class ReverseList {
interface NodeList {
int getItem();
NodeList nextNode();
}
void reverse(NodeList node) {
}
public static void main(String[] args) {
}
}
我很困惑因为我不知道接口对象可以用作方法参数。面试官解释了一下,但我仍然不确定。有人可以启发我吗?
I was confused because I did not know an interface object could be used as a method parameter. The interviewer explained a little bit but I am still not sure about this. Could somebody enlighten me?
推荐答案
这实际上是使用界面最常用和最有用的方法之一。接口定义了一个契约,你的代码可以与任何实现接口的类一起工作,而不必知道具体的类 - 它甚至可以用于编写代码时尚不存在的类。
This is in fact one of the most common and useful ways to use an interface. The interface defines a contract, and your code can work with any class that implements the interface, without having to know the concrete class - it can even work with classes that didn't exist yet when the code was written.
Java标准API中有许多示例,尤其是在集合框架中。例如,收藏集.sort()可以对实现 List
接口的任何内容进行排序(不只是 ArrayList
或 LinkedList
,虽然实现你自己的 List
是不常见的),其内容实现 Comparable
接口(不只是 String
或数字包装类 - 并且为此目的拥有自己的类实现 Comparable
相当常见)。
There are many examples in the Java standard API, especially in the collections framework. For example, Collections.sort() can sort anything that implements the List
interface (not just ArrayList
or LinkedList
, though implementing your own List
is uncommon) and whose contents implement the Comparable
interface (not just String
or the numerical wrapper classes - and having your own class implement Comparable
for that purpose is quite common).
这篇关于interface作为Java中的方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!