Interfaces

An interface is like a class. Phew! Nothing complicated here then. But it's like a class which is always abstract and with only abstract methods.

We can think of an interface as an entirely abstract class with all its methods abstract and no member variables either.

Note

OK, so you can just about wrap your head around an abstract class because at least it can pass on some functionality in its methods that are not abstract and serve as a polymorphic type. But seriously this interface seems a bit pointless.

Let's look at the simplest possible generic example of an interface, then we can discuss it further.

To define an interface, we type:

public interface myInterface{

   void someAbstractMethod();
   // OMG I've got no body
   
   int anotherAbstractMethod();
   // Ahhh! Me too

   // Interface methods are always abstract and public implicitly 
   // but we could make it explicit if we prefer

   public abstract explicitlyAbstractAndPublicMethod();
   // still no body though
   

}

The methods of an interface have no body because they are abstract, but they can still have return types and parameters, or not.

To use an interface after we have coded it, we use the implements keyword after the class declaration.

public class someClass implements myInterface{

   // class stuff here

   /* 
      Better implement the methods of the interface 
      or we will have errors.
      And nothing will work
   */
   
   public void someAbstractMethod(){
      // code here if you like 
      // but just an empty implementation will do
   }

   public int anotherAbstractMethod(){
      // code here if you like 
      // but just an empty implementation will do

      // Must have a return type though 
      // as that is part of the contract
      return 1; 
   }
}

This enables us to use polymorphism with multiple different objects that are from completely unrelated inheritance hierarchies. If a class implements an interface, the whole thing (object of the class) can be passed along or used as if it is that thing, because it is that thing. It is polymorphic (many things).

We can even have a class implement multiple different interfaces at the same time. Just add a comma between each interface and list them after the implements keyword. Just be sure to implement all the necessary methods.

In this book, we will use the interfaces of the Android API coming up soon and in Chapter 18: Introduction to Design Patterns and much more! onwards we will also write our own. In the next project, one such interface we will use is the Runnable interface that allows our code to execute alongside but in coordination with other code.

Any code might like to do this, and the Android API provides the interface to make this easy. Let's make another game.