The List interface in Java provides a way to store the ordered collection
List interface is implemented by the classes of ArrayList.
Interfaces says that class must be able to do something. Interface is an abstraction. Interfaces are just contracts or signatures and they don't know anything about implementations. It can give you a chance to support many principles of OOP.
One of the design principle says:
program to interfaces, not implementations
Let me show an example via C#. I am sorry I am not Java guy. But I have not used any special feature of C#. I've added comments how it can be looked in Java.
We should create an interface:
interface IVehicle
{
void Run();
}
and its concrete implementations:
public class Car : IVehicle // Java: Car implements IVehicle
{
public void Run()
{
Console.WriteLine("I am Car");
}
}
public class Plane : IVehicle // Java: Plane implements IVehicle
{
public void Run()
{
Console.WriteLine("I am Plane");
}
}
public class Sale : IVehicle // Sale: Plane implements IVehicle
{
public void Run()
{
Console.WriteLine("I am Sale");
}
}
Imagine that we have the following method:
void Run(Car car)
{
car.Run();
}
The above method can run only concrete type such as Car
.
Let's refactor the above method and apply design principle program to interfaces, not implementations. As a parameter, we will use an interface:
void Run(IVehicle vehicle)
{
vehicle.Run();
}
As a result, now your method can run any vehicle, it doess not depend on concrete implementation of IVehicle
such as Car
, Plane
, Sale
.
And another reason to program interfaces is it is simpler to mock interfaces.