Explaining Interfaces to Students [closed]

If you are trying to explain it to beginners I would stick with the idea that interfaces can promote code reuse and modularity within the code:

For example lets say we are going to paint some objects:

public class Painter {
    private List<Paintable> paintableObjects;

    public Painter(){
       paintableObjects = new ArrayList<Paintable>();
    }

    public void paintAllObjects(){
        for(Paintable paintable : paintableObjects){
            paintable.paint();
        }
    }
}

public interface Paintable {
     public void paint();
}

Now you could explain to the students that without Paintable interface the Painter object would need to have methods to paint certain types of objects, like a method called paintFences() and paintRocks() and we would need to have a new Collection for each type of objects we want the painter to be able to paint.

But thankfully we have interfaces which make painting objects a breeze and how objects are painted is left entirely up to classes that implement the Paintable interface.

EDIT

Another benefit that I forgot to mention is that if you ever need to add new object to paint to your code base, all you need to do is create a new class that implements Paintable and the Painter class never has to change. In this sense the Painter class is never dependent upon the objects it is going to paint, it only needs to be able to paint them.

EDIT 2

James Raybould reminded me of a key use of interfaces I forgot to mention: Having an interface between your components, like the Paintable objects and Painter objects, allows you to more easily develop with other people. One developer can work on the Painter objects and another can work on the Paintable objects and all they have to do to function properly together is define a common interface beforehand that they will both use. I know when I’ve worked on projects with other people in college level projects its really helpful when you are trying to have everyone work on different parts of the project and still have all components come together nicely in the end.

Leave a Comment