Java Specialists' Java Training Europehome of the java specialists' newsletter

The Java Specialists' Newsletter
Issue 0062001-01-25 Category: Language Java version:

GitHub Subscribe Free RSS Feed

Implementation code inside interfaces

by Dr. Heinz M. Kabutz
Abstract:
Did you know that it is possible to define inner classes inside interfaces? This little trick allows us to create method objects inside an interface.

Welcome to the 6th issue of The Java(tm) Specialists' Newsletter, a weekly newsletter appearing each Thursday, which explores some of the interesting parts of the Java(tm) language. My company, Maximum Solutions, has been very active with Java programming, consulting, training and mentoring. I particularly want to thank my client DataVoice (Pty) Ltd in Stellenbosch, South Africa, for giving me the opportunity to spend hours programming in Java on one of the first real Java projects in South Africa, perhaps even the biggest, with more lines of pure Java code than the JDK 1.3, and actually paying me to have fun.

Last night I worked on one of my most successful programs. It was a small 56 line program that I wrote in QuickBasic in April 1988, which my dad, who has a drinking straw manufacturing company, has used, with only minor modifications, to print thousands and thousands of labels for the boxes in which he packs his drinking straws. Perhaps one day you will see the logo "Maximum Solutions, the QuickBasic specialists!"

It's a terrible program, impossible to decipher, even contains a GOTO statement (!) but it does the job extremely reliably. I had to change his address last night (yes, it's hard coded!) and was thinking about what effort would be involved in writing the same program in Java. I would probably store all the customer details in an Access database, have autocompleting combo boxes, etc., but it would cost a fortune in time and energy to produce, far more than I could save by making it "nicer".

It is very important that as Java enthusiasts we keep an objective view of what applications lend themselves to Java and which do not. Otherwise we might find that we end up with something that is too expensive or too slow for its intended purpose. Overselling Java might benefit us in the short term, as companies scurry to hire us, but will damage us if Java gets a bad name. A Java Architect can command a salary of US$ 170'000 in USA at the moment, let's live up to the expectation and be responsible in our claims.

NEW: Please see our new "Extreme Java" course, combining concurrency, a little bit of performance and Java 8. Extreme Java - Concurrency & Performance for Java 8.

Implementation code inside interfaces

Now to the trick of the week, which is something you should never need to do. Please avoid doing this under all circumstances, because there are much better places to put method code than in interfaces, but I want to show you what is possible with inner classes. The call-back mechanism shown below is actually quite useful at times, especially if you want to make asynchronous database updates, but that is a topic for another newsletter.

I want to thank Niko Brummer from DataVoice for this idea, although he vehemently denies having ever really resorted to writing implementation code in an interface. Niko is a very deep person who likes to think of alternative ways of doing things, so thanks to Niko for this crazy idea :)

/**
  This interface contains an interfaces representing a Method and an
  interface showing the Result of the method call using the callback
  pattern.  It also contains a data member (automatically public static
  final) which is an anonymous inner class implementing our Method
  interface.
*/
public interface CodeInsideInterface {
  public interface Method {
    public void run(Result callback);
  }
  public interface Result {
    public void result(Object answer);
    public void exception(Exception problem);
  }
  Method calculateIQ = new Method() {
    // I always write my data members as final if possible, this catches a
    // lot of bugs at compile time
    private final java.io.BufferedReader stdin = new java.io.BufferedReader(
      new java.io.InputStreamReader(System.in));
    public void run(Result callback) {
      int iq = 100;
      try {
        System.out.print("Do you know Java (y/n)? ");
        if ("y".equals(stdin.readLine())) iq += 20;
        System.out.print("Do you know QuickBasic (y/n)? ");
        if ("y".equals(stdin.readLine())) iq += 20;
        System.out.print("Do you use the Basic GOTO statement (y/n)? ");
        if ("y".equals(stdin.readLine())) iq -= 30;
        System.out.print("Do you frequently use Java reflection (y/n)? ");
        if ("y".equals(stdin.readLine())) iq -= 50;
        callback.result(new Integer(iq));
      } catch(java.io.IOException ex) {
        callback.exception(ex);
      }
    }
  };
}

/**
  This test class demonstrates how to call the method on the interface.
 */
public class CodeInsideInterfaceTest implements CodeInsideInterface {
  public static void main(String[] args) {
    CodeInsideInterfaceTest test = new CodeInsideInterfaceTest();
    test.calculateIQ.run(new CodeInsideInterface.Result() {
      public void result(Object answer) {
        System.out.println("Your IQ is " + answer);
      }
      public void exception(Exception ex) {
        ex.printStackTrace();
      }
    });
  }
}

Well, there you go. Try and understand what is happening in the code, because it will teach you something about inner classes and how the callback mechanism works.

In the first newsletter I mentioned something about having multiple event queues in AWT / Swing and how I didn't know what the purpose is. Last Sunday I was pondering how I could possibly catch ALL events that occur in AWT / Swing and after playing around for a few hours managed to figure out how the event queues work. Next week I will show you the answer to my question in the first newsletter, i.e. why does AWT allow more than one event queue, how does it work, and what practical application is there... Send me email if you want to get back copies of newsletters. We are working on a web archive.

Regards

Heinz

Language Articles Related Java Course

Extreme Java - Concurrency and Performance for Java 8
Extreme Java - Advanced Topics for Java 8
Design Patterns
In-House Courses

© 2010-2016 Heinz Kabutz - All Rights Reserved Sitemap
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. JavaSpecialists.eu is not connected to Oracle, Inc. and is not sponsored by Oracle, Inc.