Why would you declare an Interface and then instantiate an object with it in Java?

后端 未结 10 1312
再見小時候
再見小時候 2020-12-13 06:41

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my frie

10条回答
  •  时光取名叫无心
    2020-12-13 07:43

    Program to an interface rather than an implementation.

    When you program to an interface you will write code that can handle any kind of Vehicle. So in the future your code, without modification, should work with Trains and Planes.

    If you ignore the interface then you are stuck with CArs and Bikes, and any new Vehicles will require additional code modifications.

    The principle behind this is:

    Open to Extension, Closed to Modification.

提交回复
热议问题