Why do you assign an objects to an interface?

前端 未结 6 1044

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:07

    LinkedList name = new LinkedList<>();
    

    Will expose the methods that are defined in LinkedList and its superclasses.

    Queue name = new LinkedList<>();
    

    Will expose the methods that are defined in Queue and the interfaces it extends.

    You should define the object as a class/interface that holds everything (methods, variables, etc) that you need, while also making it as abstract as possible.

    This hides implementation details and allows for easier switching between implementation, for example.

    Note that you don't have to specify the type in the initialization due to the diamond operator.

提交回复
热议问题