Interfaces and Abstract classes confusion in Java with examples

后端 未结 7 947
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 13:55

I\'m having trouble understanding when to use an interface as opposed to an abstract class and vice versa. Also, I am confused when to extend an interface with another inter

7条回答
  •  情书的邮戳
    2020-12-25 14:22

    This is a question that comes up very often, yet there is no single "right" answer that will please everyone.

    Classes represent is-a relationships and interfaces represent can-do behaviour. I usually go by a few empirical rules:

    • Stick with a class (abstract/concrete) unless you are certain that you need an interface.
    • If you do use interfaces, slice them into very specific functionality. If an interface contains more than a few methods, you're doing it wrong.

    Further, most examples of shapes and persons (or vampires for that matter!) are usually poor examples of real-world models. The "right" answer depends on what your application requires. For instance, you mentioned:

    class Vampire extends Monster implements Dangerous, Lethal, BloodSuckable
    

    Does your application really need all these interfaces? How many different types of Monsters are there? Do you actually have classes other than Vampire that implement BloodSuckable?

    Try not to generalize too much and extract interfaces when you have no need for them. This goes back to the rule of thumb: stick with a simple class unless your use case demands an interface.

提交回复
热议问题