Question

Folks can you explain me in which condition I should go with Interface and at which condition should I prefer Abstract class ... ? keep in mind I am not asking difference between Interface and Abstract class.

Was it helpful?

Solution 4

We must preferred first to inferface. If we have to write some common functionality in that class then and only then you can go for abstract class. Otherwise use interface. Because We can implement number of interface but we can extend only one class so for future you must go for interface rather than abstract class.

OTHER TIPS

If you found any Is a relationships between objects you can use abstract for example: Bird, Aeroplane, Paper Rocket these all are flyable but there is no any Is a relationship between these objects, so you can use here interface instead of abstract, Because Bird,Aeroplane and Paper Rocket all are flyable but the way of flying is different.

And off course lots of differences are on Google.

Use Abstract class when : You have some common functionality (method) which must be implemented at only one place and other concrete classes can just use it.

Use Interface when : There is no common functionality. Every concrete class has its own implementation of functionality.

I would suggest to stick to the following rules:

  • use an abstract class only, if you need code-reuse
  • restrict the visibility to the package the abstract class is defined

Otherwise use an interface and delegation. But as it is with software design you have to make the proper decision for each concrete situation. If you have restriction / rules which must be applied but need some flexibility, think about using the strategy-pattern in preference to inheritance.

The problem with abstract classes is that you can't inherit from more then one. Hence, if you need a type which is of type A and B and both are abstract classes, how do you achieve this? Interfaces are open to be implemented by any other type without restrictions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top