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
The major benefit of using interfaces, IMHO, is being able to test easily. Suppose you have an interface called, PatientManager.
You can write specific unit tests for imaginable things like "CachingPatientManager" or "LDAPPatientManager", the use case could be myriad.
The benefit is because the programming to interface becomes highly reusable and testable.
It's not the interface "object" being passed to the method, still just a regular object. It's just a way of saying "this parameter will accept any object that supports this interface". It's equivalent to accepting some object of a base class type, even if you're passing in a subclass.
This is called programming to interfaces. You don't code to a specific implementation class of node lists but to the interface implemented by all those implementations.
That way your code will still work if someone writes a new and much better implementation of NodeList
after you wrote your reverse method and you don't have to adapt your code for each new implementation of NodeList
.
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
You cannot create an instance (/object ) of an Interface. Yes, you can pass Interface as a parameter in the function. But the question seems incomplete. Interface isn't implemented by any class. Something is missing. If you try to run this, compiler will not show any error.
But, in the reverse() method you need to create an instance of class that implements NodeList interface. I hope this makes sense.
Had this same confusion while learning lambda stuff. This video didnt explain the concept, but it's a clear way for you to see how it works in terms of passing an interface as a parameter.
https://www.youtube.com/watch?v=mk3erzL70yM