Possible Duplicate:
How list methods works in java
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.
Here list is a reference to an object, not an object itself. When you call interface methods on this reference, you are actually calling the overridden methods of some concrete class that this reference points to.
To illustrate
That is the power of interfaces, I can do stuff with this reference without worrying about how it works or how it is implemented.