tags:

views:

71

answers:

3

Possible Duplicate:
Interface vs Base class

I was just thinking about when should some one go for Interface rather than an abstract class. I know interface is useful for multiple inheritance but apart from that what other advantages it provides over abstract class?

A: 

A class can implement multiple interfaces, but can inherit only one abstract class.

Further more there is a difference in semantics. Inheriting a class denotes a is-a relation, while implementing an interface, you get a has-a relationship.

Using interfaces in combination with composition (called the strategy pattern) allows for a very flexible design, which can be altered at runtime.

Ikke
Eh, no. Implemeting an interface is also an `is-a` relationship. A `has-a` relationship is when one class encapsulates another (i.e. holds an instance of the class as a member field or property). e.g. A car `is-a` Vehicle `public class Car: IVehicle`, but a car `has-a` steering wheel `SteeringWheel sh = car.SteeringWheel;`.
Binary Worrier
implement interface: behaves like Y;extend class: is-a Y;but your strategy-pattern argument is a good one as i stated in my post.
atamanroman
+2  A: 

Interfaces define a contract of behaviour. Use abstract classes when you want to provide shared implementation or common code etc.

Interfaces are used to say a given type provides an implementation so that the code expecting the interface knows how to process it. It allows polymorphic behaviour in that as long as your custom class implements the interface, my public API can take your class as my interface and work with it.

Abstracts provide implementations to derived types, interfaces ask for implementations on implementing types.

Adam
+1  A: 

Always prefer interfaces over abstract classes. If you need to provide some sort of implementation, create an abstract class which implements your base interface. So you can provide some implementation, while you leave the choice whether extend your abstract class or implement the interface.

Abstract classes force you to extend them in order to fulfill the contract. Since you should prefer composition over inheritance, its easier to make your own class with a private instance of your class x which implements interface y and implement y with your wrapper too than extending a abstract class. (e.g. Strategy Pattern)

Have a look at effective java, item 18 for further information.

atamanroman