Why is an interface or an abstract class useful? (or for what?)

前端 未结 2 1827
闹比i
闹比i 2020-12-21 07:28

So my question is, why to use interfaces or abstract classes? Why are they useful, and for what?

Where can i use them intelligently?

2条回答
  •  萌比男神i
    2020-12-21 07:46

    They're useful when you want to specify a set of common methods and properties that all classes that implement/inherit from them have, exposed behaviors that all should provide.

    Particularly about interfaces, a class can implement multiple interfaces, so this comes in handy when you're trying to model the fact that its instances must exhibit multiple types of behavior.

    Also, as Wikipedia puts it, an interface is a type definition: anywhere an object can be passed as parameter in a function or method call, the type of the object to be exchanged can be defined in terms of an interface instead of a specific class, this allowing later to use the same function exchanging different object types: hence such code turns out to be more generic and reusable.

提交回复
热议问题