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?
Generic namespace. For more information about these interfaces, see Generic interfaces. When an interface is specified as a constraint on a type parameter, only types that implement the interface can be used. The following code example shows a SortedList<T> class that derives from the GenericList<T> class.
There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
Parameters and Arguments Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With