As we know methods in interface don't have bodies...then how come methods of list, set, sortedset, navigable set work without body.. Please explain? looks like simple question but I am not able to give it a thought?
1 Answers
Interface defines the contract which must be followed by the classes implementing the interface.
Interface is Abstraction. We define the method (function) signatures in Interface. java.util.List
is an interface. java.util.ArrayList
is a concrete class implementing the interface List
. The method implementation are present in ArrayList
. Similarly LinkedList
is another concrete Implementation of List
.
User code works with object, object are of one of the concrete implementation. We can not have an object of an interface. There may be a class where you only see fields ( variables ) of type List
are present. But in such a case there must be some mechanism which would inject concrete implementation to such fields.
Methods of Interface can not work until unless some class provides concrete implementation. We can refer the objects of concrete implementation using a reference variable defined of type Interface. Like
List<String> listObj = new ArrayList<>();
Now whenever we call listObj.add("alpha");
then it is actually the method defined by concrete implementation (in this case ArrayList) which is executed. Note that above we have used direct assignment for listObj
, in actual code this may happen in constructor or setter method.

- 5,204
- 4
- 33
- 55