Below I have a Person interface, an implementing class and a driver class which initialises the Person with a name and just outputs it again. What is the advantage of using
This is the way to use interfaces.
The reason is so you could write another implementation later without changing code that uses Person
.
So for now you can use PersonImpl
but later you might need a OtherTypeOfPersonImpl
.
You could create the new class implementing the same interface, and you could use the new class with any other code that expects a Person
.
A good example is the List
interface.
There are multiple implementations of List
such as ArrayList
, LinkedList
, etc. Each of these has advantages and disadvantages. By writing code that uses List
, you can let each developer decide what type of List
works best for them and be able to handle any of them without any changes.