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.
This is good programming practice as this one Custom Canvas class can be used by many different calling applications, even within the same project. These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way. |