Reputation: 21
Can anyone elaborate the need of Interface, when we already have Abstract classes?
Upvotes: 0
Views: 100
Reputation: 31
An abstract class is better to use when its children share a lot of common pre-defined functionality but still differentiate in important ways (hence the need for abstract methods and why you can't instantiate an abstract class)
Inheritance is simply a "contract" on what a class implementing that interface must do.
Inheritance allows for greater polymorphism..
Upvotes: 0
Reputation: 76817
You can achieve anything you want using only abstract classes instead of interfaces if you consider the syntax, but there is a semantic difference. An abstract class can have implemented methods which will be inherited in subclasses, so it can have defined behaviors, while interfaces can only have declared behaviors.
On project-management level there are cases when the leader decides that you should write declarations and you should not have the possibility to implement them. In that case they tell you to implement an interface and they will know that as long as the thing you create is an interface, all the methods will be forced to be implemented in classes which implement it. Also, if you encounter an abstract class, you might want to implement one of its methods, without knowing that it should not be implemented on that level of the hierarchy. So, interfaces are actually good to have a way to make sure that some behaviors are declared, but not defined.
Upvotes: 1