The purpose of interfaces continued

后端 未结 13 1444
轮回少年
轮回少年 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:39

    If you are creating a number of classes all implementing such features and the implementation is only slightly different, this is going to be a lot of hard work.

    In that case you are easily allowed to create another layer in you hierarchy of classes which implements Animal but is an ancestor class for all animals that eat in some way, for example

    class Herbivore implements Animal {
      public void eat(Object food) {
       ...
      }
    }
    
    class Cow extends Herbivore..
    class Horse extends Herbivore..
    

    and you are allowed to override eat by using super.eat() and changing only the slight part..

    You should look forward code reuse and encapsulation of components at the same time.. then if your interface really doesn't characterize the class itself but just a component of it you can go by composition as suggested by Carl Manaster.

提交回复
热议问题