How list methods works in java [closed]

2020-05-11 00:01发布

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.

4条回答
疯言疯语
2楼-- · 2020-05-11 00:21

java.util.ArrayList, java.util.LinkedList, java.util.Vector are concrete implementation class of List interface. This classes contains all method implementation. You can use like -

List<String> list = new ArrayList<String>();
查看更多
The star\"
3楼-- · 2020-05-11 00:26

enter image description here

Java provides 3 concrete classes which implement the list interface
Vector
ArrayList
LinkedList
查看更多
贪生不怕死
4楼-- · 2020-05-11 00:30

"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?

查看更多
相关推荐>>
5楼-- · 2020-05-11 00:38

The only objects of type List you will be using will be types which actually implement List, like ArrayList, LinkedList etc. They will provide the implementations.

You cannot instantiate a class which has unimplemented abstract methods from super classes or interfaces.

查看更多
登录 后发表回答