For a single type of class, you are not missing anything.
However, consider the following class where
Animal
is an
Interface
:
import java.util.ArrayList;
import java.util.List;
public class AnimalHospital
{
private final List<Animal> animals;
public AnimalHospital()
{
// Initially the hospital has no animals to treat.
this.animals = new ArrayList<Animal>();
}
void add(final Animal animal)
{
animals.add(animal);
}
void treatAllAnimals()
{
for(final Animal animal : animals)
animal.treat();
}
}
This
AnimalHospital
can accept any kind of animal for treatment - provided the animal's class (e.g.
Cat
,
Dog
, etc.) implements the
Animal
interface.
If, at a later date, someone creates a new animal class (such as a
DuckBilledPlatypus
) that implements the
Animal
interface then that animal can also be treated at the hospital
without any change to the hospital code. As long as it's an
Animal
then the
AnimalHospital
can handle it.
The same is also hold true if someone later extended the
Dog
to create a
Doberman
sub-class of dog.
That is power that interfaces bring to your code.