The purpose of interfaces continued

后端 未结 13 1443
轮回少年
轮回少年 2020-12-03 02:28

OK so I gather that Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance. Kind of like a contract.

13条回答
  •  青春惊慌失措
    2020-12-03 02:35

    One major reason is that you can create an object using an interface reference, similar to an abstract method. When you do this, every object which implements the interface can be assigned to it. For example, if Dog and Car both implement Washable, then you can do:

    Washable wD=new Dog();

    Washable wC=new Car();

    If Washable has the public abstract method wash(), then you can do this:

    wD.wash();

    wC.wash();

    and their respective methods will be called. This also means that you can accept an interface as a parameter for a method meaning you don't have to add unecessary code to deal with every class which implements a certain interface.

    See here for a more detailed explanation: http://www.artima.com/objectsandjava/webuscript/PolymorphismInterfaces1.html

提交回复
热议问题