One interviewer has asked me the below question and I couldn't answer:
Why do we need Interfaces when abstract classes exist?
Whatever the methods we are writing in interface those we can write in Abstract class also. Then why do we need interfaces separately?
Can anybody please tell what is the reason?
Advance thanks...
Interfaces are more flexible, because a class can implement multiple interfaces. Since Java does not have multiple inheritance, using abstract classes prevents your users from using any other class hierarchy. In general, prefer interfaces when there are no default implementations or state.
The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes. For this reason multiple inheritance is block using classes in java.
Abstract classes provide you the flexibility to have certain concrete methods and some other methods that the derived classes should implement. On the other hand, if you use interfaces, you would need to implement all the methods in the class that extends the interface.
It only contains public access modifier because everything in the interface is public. The performance of an abstract class is fast. The performance of interface is slow because it requires time to search actual method in the corresponding class. It is used to implement the core identity of class.
There are several differences,
Interfaces are great to focus on a 'view' we can have on a class. This view can be shared by multiple classes implementing the interface.
For instance, DataTable implements IListSource and ISerializable. So, depending on the context, you can view it as a list source to read its data or as a class which instances can be serialized. When you do so, you focus on a specifc view you can have of an instance.
Interface represents a contract, while you can have several implementations of that contract in different (abstract) classes.
public interface IExample
{
void Do();
}
public abstract class DoFirst : IExample
{
public void Do()
{
Console.WriteLine("Doing it the first way");
}
}
public abstract class DoSecond : IExample
{
public void Do()
{
Console.WriteLine("Doing it the second way");
}
}
public class DoFirstConcrete : DoFirst, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with first.");
}
}
public class DoSecondConcrete : DoSecond, IExample
{
public void DoSomethingElse()
{
Do();
Console.WriteLine("Doing something else also with second.");
}
}
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