Why do you assign an objects to an interface?

前端 未结 6 1017

I have heard several times that when instantiating objects you should do:

\"Interface\" name = new \"Class\"();

For example for the class linkedlist that imp

6条回答
  •  别那么骄傲
    2020-12-31 14:10

    This isn't as simple as it looks. If you use:

    List name = new LinkedList();
    

    if you ever wanted to switch from linked lists to arraylists it would be less maintenance.

    About the redundancy, List name = new LinkedList() declares name of type List and invokes the LinkedList constructor. You could have as follows:

    List name = someRandomObject.someRandomHelperMethod();
    

    This helper method "just happens" to return a list, so there is no redundancy.

    With Java 7 the apparently-redundant generic args can be skipped:

    List someL = new ArrayList<>();
    

    as opposed to

    List someL = new ArrayList();
    

提交回复
热议问题