abstract classes and interfaces best practices in java

前端 未结 5 2110
一个人的身影
一个人的身影 2021-02-10 08:37

So you\'ve got an interface and an abstract class that implements a subset of the methods in the interface. You\'ve also got some classes that inherit the abstract class and giv

5条回答
  •  -上瘾入骨i
    2021-02-10 09:32

    The principle that should help you here id DRY: Don't Repeat Yourself (http://en.wikipedia.org/wiki/Don%27t_repeat_yourself).

    In this context, DRY means that you should not do unnecessary work.

    So for your 1st question the abstract class should implement the interface because it saves you from repeating the "implements X" clause at every concrete class.

    As for the 2nd question, there's no point in repeating the interface methods in the abstract class that implements it. This is redundant work. Moreover when the interface evolves/changes you will need to change the counterparts (abstract) methods at the abstract class which is a headache. At some point you'll miss updating some of the method and the concrete class will need to implement these in vain.

提交回复
热议问题