When to implement an interface and when to extend a superclass?

后端 未结 11 814
遇见更好的自我
遇见更好的自我 2020-11-30 04:41

I\'ve been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever rea

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 05:18

    Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.

    Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).

    An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.

提交回复
热议问题