interface as a method parameter in Java

前端 未结 8 1878
一个人的身影
一个人的身影 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 20:48

    The argument needs an object, which class implements an interface (the parameter).

    In pseudo Java the code:

    void reverse(NodeList node) {
        // your code
    }
    

    is equal to:

    reverse(x) {
        if(x == null || x instanceof NodeList) {
             // your code
        }else throw new RuntimeException("Some sort of error.");
    }
    

    Note; read more on Interfaces here: http://java.sun.com/docs/books/tutorial/java/IandI/interfaceAsType.html

提交回复
热议问题