Custom Canvas -> Application using Interfaces
The previous example works very well; however, there is one major flaw. If we want to re-use our custom canvas in another application called DrawingApp then we can't without changing the code, as it requires an application called CanvasApplication to be passed. Clearly we need a way to allow the name of the calling class to change or our code will not be very portable.
To do this, we use Java Interfaces. We saw Java Interfaces before, but what they allow us to do here is to abstract the calling application to "any application that implements our Java interface"
So, here is our Java interface. At the moment there is only one method that we allow our custom canvas to call on the main application and we'll rename it slightly to setNumber(int). So, this interface below states that if any class implements the CounterField interface then it must write the code for a method called setNumber. So, our class can have any name!
So, here is the application implementing the CounterField interface. Without reading past the "public class CanvasApplication..." line, I know that there must be a setNumber(int) method, otherwise the code could not compile.
We pass the object of CanvasApplicationInterfaces directly to the constructor of the custom canvas class and it looks like the same as before; however, there is one major difference, which can be seen below - The custom canvas does not expect an object of CanvasApplicationInterfaces, it expects an object of the interface CounterField (see the constructor).
This is good programming practice as this one Custom Canvas class can be used by many different calling applications, even within the same project.