When to use an interface instead of an abstract class and vice versa?

前端 未结 23 2505
忘了有多久
忘了有多久 2020-11-22 04:29

This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.

When wou

23条回答
  •  余生分开走
    2020-11-22 05:09

    My two cents:

    An interface basically defines a contract, that any implementing class must adhere to(implement the interface members). It does not contain any code.

    On the other hand, an abstract class can contain code, and there might be some methods marked as abstract which an inheriting class must implement.

    The rare situations I've used abstract classes is when i have some default functionality that the inheriting class might not be interesting in overriding, in say an abstract base class, that some specialized classes inherit from.

    Example(a very rudimentary one!):Consider a base class called Customer which has abstract methods like CalculatePayment(), CalculateRewardPoints() and some non-abstract methods like GetName(), SavePaymentDetails().

    Specialized classes like RegularCustomer and GoldCustomer will inherit from the Customer base class and implement their own CalculatePayment() and CalculateRewardPoints() method logic, but re-use the GetName() and SavePaymentDetails() methods.

    You can add more functionality to an abstract class(non abstract methods that is) without affecting child classes which were using an older version. Whereas adding methods to an interface would affect all classes implementing it as they would now need to implement the newly added interface members.

    An abstract class with all abstract members would be similar to an interface.

提交回复
热议问题