In an interview it was asked to me to justify when to choose interface and when to choose abstract classes and in which conditions you will choose out of the two only one.. I have come up with my analysis for interface and that is...
Interface is best choice for Type declaration or defining contract between multiple parties. If multiple programmers are working in different modules of a project they still use each others API by defining interface and not waiting for actual implementation to be ready.
This brings us a lot of flexibility and speed in terms of coding and development. Use of Interface also ensures best practices like "programming for interfaces than implementation" and results in more flexible and maintainable code.
But I don't have strong reasons to justify the abstract classes, Please advise..!
Abstract classes are used to group a number of concrete classes under one entity.
For example, take the abstract class Animal
.
Animal is not something concrete. it's a family of, well, animals. but they all share certain aspectes, for example, each has a speak()
option (well, except fish and sort). but each one implements it differently. this way you can override just the methods which are not the same, for example sleep() or breath()
are common (again, fish are differnet :) ).
Interfaces on the other hand are more direct definition of an 'action'. That's why most (if not all) the interfaces in Java ends with 'able' (Comprable, Serializable...) By implementing the interface, you're telling other programmers or who ever uses your code that this class can do this and this. A dog, for example, is not, Animable.
Basically, to sum it up, I think that the best definition is this.
Use abstract classes when you have a class that A is kind of B
and interface when A can do B
.
Hope that's help.
Abstract classes are used when you want to provide partial implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With