接口作为Java中的方法参数 [英] interface as a method parameter in Java
问题描述
几天前我接受了一次采访,被抛出了这样的问题.
I had an interview days ago and was thrown a question like this.
Q:反转链表.给出如下代码:
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).
这篇关于接口作为Java中的方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!