Can you help me understand in a practical example the usage abstract classes vs interfaces?

前端 未结 9 669
孤城傲影
孤城傲影 2020-12-24 04:09

Can you give me an almost overly simplistic understanding of abstract class vs inheritance use and help me so I can truly understand the concept and how to implement? I have

9条回答
  •  感动是毒
    2020-12-24 04:56

    You're close, but making this tougher than it needs to be.

    I don't want to give you the answer ;) but here are a few pointers.

    First, you're creating 3 classes and 1 interface. However, the one thing I believe you may be missing is that you need 3 different types of objects here (from "least defined" to "most defined"):

    1) Interface
    This is IAnimal - and can be implemented by anything that can act like an animal

    2) Abstract Base Class This is the Animal calss - anything that IS an animal should derive from Animal, but these aren't creatable directly. If you pretend you're God, you don't make an Animal, you make a Dog, Cat, Squirrel, or FuzzyBunny

    3) Concrete Implementation of Animal These are the actual classes themselves. This is what you create. Dog or Cat in your case.

    The trick here is that you can only create concrete classes, but you can use IAnimal or Animal (interfaces or abstract base classes) to manipulate and work with any animal (or, in the case of interfaces, anything that acts like an animal)

提交回复
热议问题