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

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

    To be honest it scares me the amount of people in the industry that don't know this regardless of whether it is a homework question or not. Therefore I will answer.

    Interfaces abstract implementation and so do abstract classes. There is no "vs" because you can create an abstract class that implements an interface too. So don't think they're at war with one another.

    Therefore EITHER can be used when you don't want the consumer to know too much about the implementation. An interface is a bit better at this job because it has no implementation, it just states what buttons the consumer can press the values they get back and send where an abstract class may state a bit more than this (or even a lot more!). So if you just take this point onboard you only really need interfaces. Ergo, point two:

    As abstract class is used when you want to share common code between two different implementations of an interface. In this scenario two concrete implementations both inherit from the abstract class which implements the interface.

    Simple example is IDataStore. SavingToATextFile datastore is just a class that implements IDataStore. However MsSqlDataStore and MySqlDataStore will share common code. They will both inherit from the abstract class SqlDataStore which implements IDataStore.

提交回复
热议问题