Running on Java 22-ea+15-1134 (Preview)
Home of The JavaSpecialists' Newsletter

006Implementation Code Inside Interfaces

Author: Dr. Heinz M. KabutzDate: 2001-01-25Java Version: 1.1Category: Language
 

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.

javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge.

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

 

Comments

We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Related Articles

Browse the Newsletter Archive

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '23

Superpack '23 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...