Interface versus concrete class

前端 未结 5 702
北荒
北荒 2021-02-05 12:06

Below I have a Person interface, an implementing class and a driver class which initialises the Person with a name and just outputs it again. What is the advantage of using

5条回答
  •  梦谈多话
    2021-02-05 13:05

    This is the way to use interfaces.

    The reason is so you could write another implementation later without changing code that uses Person.

    So for now you can use PersonImpl but later you might need a OtherTypeOfPersonImpl.

    You could create the new class implementing the same interface, and you could use the new class with any other code that expects a Person.

    A good example is the List interface.

    There are multiple implementations of List such as ArrayList, LinkedList, etc. Each of these has advantages and disadvantages. By writing code that uses List, you can let each developer decide what type of List works best for them and be able to handle any of them without any changes.

提交回复
热议问题