2001-01-25 The Java™ Specialists' Newsletter [Issue 006] - Implementation code inside interfaces

Author: Dr. Heinz M. Kabutz

(C)opyright Maximum Solutions, South Africa

If you are not already subscribed to this newsletter, you can either subscribe via email or subscribe via the web. Be warned that if you are a beginner in Java, you will at times struggle to keep up.

Welcome to the 6th issue of "The Java™ Specialists' Newsletter", a weekly newsletter appearing each Thursday, which explores some of the interesting parts of the Java™ 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 my 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.

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


(C)opyright Maximum Solutions, South Africa

The Fine Print
Mission. This newsletter began at the end of 2000 with about 150 readers that I had gleaned from my contacts list. Since then, it has grown to its current readership exceeded 1'000 readers, necessitating a move to a "proper" mailing system. It's goal is to share some advanced ideas and thoughts on Java programming and the way that a Java specialist would deal with problems "in the field". Carl Smotricz is currently hosting an archive of past newsletters.
Reprint Rights. Copyright subsists in all the material included in this email, but you may freely share the entire email with anyone you feel may be interested, and you may reprint excerpts both online and offline provided that you acknowledge the source as follows: This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa) - The Java(tm) Specialists. Please contact Dr. Heinz M. Kabutz (h.kabutz@computer.org) for more information.


Please contact me if you would like to put a link to this newsletter on your website.