Why is an interface or an abstract class useful? (

2019-01-28 09:41发布

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条回答
Deceive 欺骗
2楼-- · 2019-01-28 10:24

Interfaces allow you to express what a type does without worrying about how it is done. Implementation can be changed at will without impacting clients.

Abstract classes are like interfaces except they allow you to provide sensible default behavior for methods where it exists.

Use and examples depend on the language. If you know Java, you can find examples of both interfaces and abstract classes throughout the API. The java.util collections have plenty of both.

查看更多
虎瘦雄心在
3楼-- · 2019-01-28 10:29

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.

查看更多
登录 后发表回答