3

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

Where can i use them intelligently?

therufa
  • 2,001
  • 2
  • 25
  • 39

2 Answers2

5

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.

duffymo
  • 293,097
  • 41
  • 348
  • 541
  • Since JDK 8 it's possible to add default behavior to interfaces. Abstract classes are still different because they can have state. Interfaces can only declare static variables. – duffymo Nov 22 '17 at 12:53
3

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.

luvieere
  • 35,580
  • 18
  • 120
  • 178