Press enter to see results or esc to cancel.

What is an Interface?

What is an interface and what is it good for? This article was written for beginners that may have programmed a while but have not yet encountered or found any use for interfaces. After this article the reader will have more knowledge about interfaces, what they’re actually good for and how to implement them.

What is an interface?

Interfaces are often described as “contracts”. For a beginner, this may not make much sense. A contract? For what? Between whom? So let’s unpack that first.

Interfaces are often described as contracts because when an interface is defined and a class implements said interface (i.e. explicitly uses it) then everything that is declared in the interface must also be implemented in the class. So you could say that once the class signs the contract (the interface) it needs to abide by it.

How Do you Define an Interface?

  • It depends on the programming language, but generally, you use the keyword Interface, the name and its body.
  • The body is just the signature of every method each class must have; The method return type (if applicable), its name and any parameters.
  • The methods cannot have any body. It’s up to each class to implement it each interface method.
// here are a couple of interfaces in java
public interface Animal {
   public String sound();
}

public interface Weapon {
   public int doDamage();
   public void break();
}

public interface Character {
   public void loseHealth(int health);
   public void gainHealth(int health);
   public void run();
   public void walk();
   public String talk();
}
// and here are the same interfaces in PHP

// without return type declarations (< PHP7)
public interface Animal {
   public function sound();
}

// with return type declarations (>= PHP7)
public interface Weapon {
   public function doDamage() : integer;
   public function break() : void;
}

public interface Character {
   public function loseHealth(Int $health) : void;
   public function gainHealth(Int $health) : void;
   public function run() : void;
   public function walk() : void;
   public function talk() : string;
}

How to implement an interface

  • You generally use the keyword implements right after the class name followed by the interface name.
  • You can implement multiple interfaces separated by a comma.
  • Finally, you implement the interface’s methods in the class body.
// Implement an interface in java
class Sword implements Weapon {
   public int doDamage() {
      // do damage
   }
   
   public void break() {
      // break weapon
   }
}

// Implement multiple interfaces in java
class Player implements Animal, Character {
   public String sound() {
      // make animal sound
   }

   public void loseHealth(int health) {
      // lose health
   }

   public void gainHealth(int health) {
      // gain health
   }

   public void run() {
      // run
   }

   public void walk(){
      // walk
   }

   public String talk() {
      // talk
   }
}

Short Example 1 – Chores

Let’s say you have an interface called Chores with two methods; doTheDishes() and takeOutTheTrash().

Every class that implements the Chores interface (i.e. signs the contract) MUST have two methods called doTheDishes() and takeOutTheTrash(). It’s set in stone. Unescapable. However, how you implement these methods, that is, how each method should work is completely up to you.

Person A could, for instance, implement these two methods just like you would expect someone to handle the chores; scrub the plates, and put the trash in the garbage can outside.

Person B however, could implement these methods in a completely different way; use a secret scrubbing technique or even go and buy new plates, as long as they’re clean.

Both versions result in the same thing but their inner workings are different.

public interface Chores {
   public void doTheDishes();
   public void takeOutTheTrash();
}

// Person A implements it in one way
class PersonA implements Chores {
   public void doTheDishes(){
      // scrub the plates the normal way
   }

   public void takeOutTheTrash(){
      // take out the trash
   }
}

// Person B implements it in another way
class PersonB implements Chores {
   public void doTheDishes(){
      // scrub the plates with a secret technique
   }

   public void takeOutTheTrash(){
      // take out the trash
   }
}

// Person C does not implement the interface correctly
class PersonC implements Chores {
   public void doTheDishes(){
      // scrub the plates with a secret technique
   }

   // takeOutTheTrash() is not implemented so the compiler 
   // will throw an error until it is implemented.
}

Short Example 2 – Cars

Imagine a car. Every car can start, accelerate and drive. An interface in this case could define the methods start(), accelerate() and drive(). Now anything with four wheels that wants to call itself a car must implement the interface and its three methods.

Of course, every car is different and aside from the three mandatory methods start(), accelerate(), and drive() they can implement their own unique methods. Tesla’s could for example implement a unique playGame() or autopilot() method.

interface Car {
   public function start();
   public function accelerate();
   public function drive() : string; // returns a string
}

// Volvo implements it in one way
class Volvo implements Car {
   public function start(){
      // start the car the volvo way
   }

   public function accelerate(){
      // accelerate the car the volvo way
   }

   public function drive() : string {
      return "Vroooooom";
   }
}

// Tesla implements it in another way
class Tesla implements Chores {
   public function start(){
      // start the car the tesla way
   }

   public function accelerate(){
      // accelerate the car the tesla way
   }

   public function drive() : string {
      return "vroom";
   }

   public autopilot(){
      // Do autopilot magic
   }
}

Short Example 3 – Lightsabers

One last example. What do all lightsabers have in common? They do a cool hummingNoise(), they can doDamage() and toggle() on and off. To be able to call it a lightsaber it has to implement the lightsaber interface and its methods. It HAS to have a humming noise, be able to do damage and have an on/off button.

Now you can create a thousand different lightsaber classes with an abundance of unique bells and whistles and still be 100% sure that every single one of them can make a humming noise, do damage and toggle on/off no matter how different they are. And you cannot accidentally create a lightsaber without each of these methods.


Okay, so now you know that each class that implements an interface must contain all of the interface’s methods. You also know that the class can implement the methods in any way it wants or needs to and that a class can implement multiple interfaces.

Question 1: Are the classes only allowed to have the interface methods and nothing else?

Answer: No. How you write your classes is completely up to you. The interface does not care what’s in your classes as long as they also contain the interface’s defined methods. It only enforces its own methods upon the class, no more no less.

Question 2: What happens if the class doesn’t implement one or all methods of an interface?

Answer: The compiler simply throws an error. It basically says, “Hey programmer, this class signed a contract but it’s not following it. Implement everything in the contract.”. The actual type of error depends on the programming language.

Question 3: What kind of code goes into an interface?

Answer: You only define the methods, i.e. put the method signature in the interface. No body. The implementations are done in each separate class.

What is an interface good for?

So now you that an interface is a contract that any class can sign and its method implementations are up to the programmer. Finally, if the class doesn’t implement everything an error will be thrown. So what is an interface good for exactly?

  • Interfaces makes it easy to use a variety of classes in the same way; If two objects implements the same interface you can be 100% sure you can call the methods no matter which object.
  • It gives you the flexibility to avoid multiple inheritance (in languages that allow this) from other classes but still force a class to implement multiple interfaces.
    See the diamond problem. It’s an ambiguity problem. Imagine 4 classes. Class A, B, C and D where class B and C inherits from class A. Class D inherits from both B and C.
    If B and C has overridden a method inherited from A but D does not override that same method – which method version is actually used in A? Is it the method inherited from B or C?
  • They provide a conceptual and abstract contract for classes to implement.
  • In some programming languages you cannot inherit from multiple classes, but you can implement multiple interfaces.
  • They can act as both mental and communication aid for programmer/s working on the same project.
  • Interfaces prevent you from making mistakes by assuring you that classes implementing an interfaces actually have all the necessary methods. They act as a failsafe against tired and/or careless programmers, which we all are from time to time.
    Do my 24 various animal classes all have the walk(), sound(), eat(), sleep() and poop() methods?

Conclusion

  • Interfaces contains public method definitions that must be in every class that implements the interface.
  • Interfaces are a contract that classes can implement. To follow the contract is to implement each of the interface’s methods in the class.
  • Using interfaces will make you, the programmer, 100% sure you can use methods the exact same way no matter what class it is.
  • They can also help avoid the diamond problem in some programming languages where you need to force classes to implement methods.
  • Finally, they can provide mental and communication aid for the programmer or programmers working on the same project as well as preventing you from making mistakes by assuring you that the class actually have all the necessary methods.