abstract classes and interfaces best practices in java

前端 未结 5 2192
无人及你
无人及你 2021-02-10 08:57

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:15

    The most flexible way to program for this is:

    1. Provide the interface
    2. Provide the abstract class that implements the interface
    3. Provide the concrete classes that either extend from the abstract class or extend from another class and implement the interface
    4. Alway (unless you cannot) declare variables/parameters/constants as the interface rather than the abstract class or concrete classes

    There is no point in having the concrete classes implement the interface (more later). There is no point in having the abstract class repeat the abstract methods from the interface.

    By doing #4 you ensure that all classes that implement the interface can be used - if you were to use the abstract class instead then classes that implement the interface but do not extend the abstract class cannot be used.

    (later part)

    The one argument for having the abstract class AND the concrete classes implement the interface is that if you were to later change the concrete class to no longer extend the abstract class then you could forget to also implement the interface, which, in some cases, could break the code without the compiler complaining. I don't know how I feel about that argument.

提交回复
热议问题