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

前端 未结 23 2143
忘了有多久
忘了有多久 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:00

    Consider using abstract classes if any of these statements apply to your situation:

    1. You want to share code among several closely related classes.
    2. You expect that classes that extend your abstract class have many common methods or fields or require access modifiers other than public (such as protected and private).
    3. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

    Consider using interfaces if any of these statements apply to your situation:

    1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    3. You want to take advantage of multiple inheritances.

    Source

提交回复
热议问题