Why do we need this thing called "interfaces"?

Why do we need this thing called “interfaces”? I googled it and found this article with this piece of code

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

You can easily remove the interface, and it would work just as well. The article says it provides more security, but I don’t see how

Hello!
I can’t speak from a place of certainty, but from my understanding, interfaces provide developers a framework to work off, so that everybody understands what a class is meant to do. Imagine if you have a team of 10 developers all working on a large codebase. (Probably) nobody is going to know all the code off the tops of their head, so by using interfaces, one developer can more easily understand another’s code, without having to read through it all. It also avoids someone extending or changing a class in a way that would break the code.

One could think of it in a similar way to the final keyword; while it isn’t necessary, it means that large teams are less likely to code bugs that will be harder to spot, and may end up causing issues further down the line.

I hope that helps!

2 Likes