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

前端 未结 9 655
孤城傲影
孤城傲影 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:37

    Basically, an interface defines a 'contract' (i.e. a set of operations/properties) that all implementers must provide. In this case the IAnimal interface requires the WhatAmI and WhatIsMyName properties. Abstract classes may provide certain functionality, yet will also leave some operations which must be implemented by their subclasses.

    In the case of your example, the Animal base class is able to provide the WhatIsMyName functionality since 'Name' is a property of all animals. However, it cannot provide the 'WhatAmI' property, since only specific subclasses know what 'type' they are.

    The problem with the sample code you posted, is that thet Animal class has knowledge of it's subclasses, which it should not have

提交回复
热议问题