List is an interface in java. And it has some methods. Generally an interface is a specification of method prototypes. i.e. interface consist of methods signature only no implementation will be there for that methods in interface.
I have a doubt that how the methods of List interface work if they don't have any implementation inside the interface.
Suppose I have a class Book which has name property, setter,getter methods. and I have another class getBooks like this.
public class GetBooks{
List<Book> list;
public List<Book> getBooks(){
return list;
}
//setter method..
}
I am sending books into the set method at runtime through some other class.
I have another class UseBooks like this.
public class UseBooks{
.....
....
List<Book> list = new GetBooks().getBooks();
list.add(new Book("aaa"));
}
My question is how add method is adding books even it is in interface List because my getBooks() returning List interface not Arraylist or some other implementation class.
java.util.ArrayList
,java.util.LinkedList
,java.util.Vector
are concrete implementation class ofList
interface. This classes contains all method implementation. You can use like -"I have a doubt that how the methods of List interface work if they dont have any implementation inside the interface" -(!!!!!!) It will use the implementation of any class instance which is implemented this interface. So depends on the implementation in different class instance.
Are you expecting any kind of detailed example for this?
The only objects of type
List
you will be using will be types which actually implementList
, likeArrayList
,LinkedList
etc. They will provide the implementations.You cannot instantiate a class which has unimplemented abstract methods from super classes or interfaces.