Benefits of using an abstract classes vs. regular class

后端 未结 9 914
独厮守ぢ
独厮守ぢ 2021-01-31 17:52

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 18:18

    Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...

    Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.

    Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).

提交回复
热议问题