interface as a method parameter in Java

前端 未结 8 1859
一个人的身影
一个人的身影 2020-11-30 20:34

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 { 
    i         


        
8条回答
  •  一整个雨季
    2020-11-30 21:07

    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.

    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).

提交回复
热议问题