Overview

Skill Level: Beginner

Follow this recipe and you will learn what anonymous classes are, and how to use them to make your Java™ code more compact and maintainable. You will finish out a Vaadin 8 application, and deploy and test it using WebSphere Liberty.

Ingredients

Step-by-step

  1. Setup your development environment

    You will need the JDK and Eclipse IDE installed to complete this recipe. I’ll assume you have some basic Java knowledge. If not, please check out the Intro to Java Programming learning path here at IBM developerWorks.

    You will also need a working development environment. If you already have a Java development environment, skip to Step 2.

    Otherwise, check out the Introduction to Java Programming learning path, Unit 2 for step-by-step instructions. There are videos in this section as well that can assist you if you need more help.

    First, download and install the Java Development Kit (JDK), version 8, and install it on your machine. Please refer to the video below if you need help.

    Next, install the Eclipse IDE to your computer. Please refer to the video below if you need help.

    Once you have your development environment setup and ready to go, you can proceed to Step 2, where I’ll show you how to install the Vaadin 4.0 plugin for Eclipse.

  2. Install the Vaadin 4.0 plugin for Eclipse

    The Vaadin 4.0 plugin for Eclipse makes it so much simpler to develop Vaadin applications in Eclipse, so I recommend you install it. Please refer to the video below, where I show you how to install the plugin, and verify that it is working properly in your Eclipse IDE.

  3. Download and install WebSphere Liberty

    The WebSphere Liberty Profile is a robust application server that is easy to install, boots up quickly, and is JEE compliant.

    Please refer to the video below, where I’ll show you how to install WLP and verify that it is working on your computer.

  4. About Vaadin

    There are lots of great Vaadin resources, and I’ll list some at the end of this recipe, but I think it’s worthwhile to give you a high level overview of the Vaadin architecture.

    The figure below shows the high-level Vaadin architecture (image credit to Vaadin docs):

    Vaadin-High-level-Architecutre-1

    The user interacts with your Vaadin application through Javascript running in the browser. Because Vaadin uses Google Web Toolkit (GWT), a large number of browsers are supported right out of the box. This code is generated for you automatically, leaving you to concentrate on your application’s business logic.

    The server side entry point for your Vaadin application is a Java servlet that communicates with backend services like databases and other business logic. Your application’s main UI class is an extension of the Vaadin framework class called, well, UI. The UI class is the view (called a view port using Vaadin terminoogy) for your application, and your application must provide at least one subclass of UI. A simple use of UI looks like this:

    @Theme("mytheme")
    public class MyApp extends UI {
    protected void init(VaadinRequest request) {
    ... initialization code goes here ...
    }
    }

    The look of your application is controlled through the use of themes, which build from a Base Theme as shown in the high-level architecture diagram. A Vaadin application separates the functionality of the application (think: business logic) from the way it appears to the user using Themes. You can learn more about Vaadin themes here.

  5. What is an anonymous class?

    An anonymous class is a special type of inner class (see Intro to Java Programming learning path, Unit 18) that functions just like any other Java language class, with the following exceptions:

    • The class has no name (which is why it is anonymous)
    • The class is instantiated only once, at the point of definition

    Consider this code, which shows a public inner class and how to define, instantiate, and use it:

    public class Outer {

      public interface Something {
        public String doSomething(String... words);
      }

      public class Inner1 implements Something {
        @Override
        public String doSomething(String... words) {
          // Just return the first word if there is one
          return (words.length > 0) ? words[0] : null;
        }
      }

      public static void main(String[] args) {
        Outer outer = new Outer();
        Something oneThing = outer.new Inner1();
        outer.doItWithCallback(oneThing);
      }

      public void doItWithCallback(Something callback) {
        callback.doSomething("Mary", "had", "a", "little", "lamb");
        callback.doSomething("42");
      }

    }

     

    No Name

    A named inner class has a name so it may be referenced in order to instantiate it. In the example above, the inner class is called Inner1. An anonymous class has no name, as I’ll show you in Step 6.

    Instantiated only once, at the point of definition

    A named inner class is usually defined in a location other than where it is used (usually at the parent class level), and may be instantiated multiple times. An anonymous class must be defined and instantiated in the same statement of code, as I’ll show you in Step 6.

     

  6. Why use an anonymous class?

    Refer back to the code example in the previous section, where the inner class Inner1 implements the Something interface. The implementation of doSomething() was very simple, yet we had to go to the trouble of defining the class. Suppose I needed another implementation of doSomething() that returns only the last word of the collection of words. I could define another inner class, so that now the code looks like this:

    public class Outer {

    public interface Something {
    public String doSomething(String... words);
    }

     public class Inner1 implements Something {
    @Override
    public String doSomething(String... words) {
    // Just return the first word if there is one
    return (words.length > 0) ? words[0] : null;
    }
    }
    // New Something implementation
    public class Inner2 implements Something {
    @Override
    public String doSomething(String... words) {
    // Just return the last word if there is one
    return (words.length > 0) ? words[words.length-1] : null;
    }
    }

    public static void main(String[] args) {
    Outer outer = new Outer();
    Something oneThing = outer.new Inner1();
    outer.doItWithCallback(oneThing);

    Something anotherThing = outer.new Inner2();
    outer.doItWithCallback(anotherThing);
    }

    public void doItWithCallback(Something callback) {
    callback.doSomething("Mary", "had", "a", "little", "lamb");
    callback.doSomething("42");
    }

    }

    Now I have cluttered my code with a second class definition. What a pain!

    There has to be a better way! (Spoiler alert: there is!)

    Before going any further, I want to stress: anonymous classes are not for every purpose, but are perfect for when:

    • You need to use an interface or abstract class implementation only once (such as with a callback method),
    • You want your code to be concise, and/or
    • You want to declutter your code. 

    I’ll show you how to create and use an anonymous class next in Step 7.

  7. Creating anonymous classes

    With an anonymous class, I could just do this, and I’m done:

    public class ConciseOuter {

      public interface Something {
        public String doSomething(String... words);
      }

      public static void main(String[] args) {
        ConciseOuter outer = new ConciseOuter();

        outer.doItWithCallback(new Something() {
          public String doSomething(String... words) {
            // Just return the first word if there is one
            return (words.length > 0) ? words[0] : null;
          }
        });

        outer.doItWithCallback(new Something() {
          public String doSomething(String... words) {
            // Just return the last word if there is one
            return (words.length > 0) ? words[words.length - 1] : null;
          }
        });
      }

      public void doItWithCallback(Something callback) {
        callback.doSomething("Mary", "had", "a", "little", "lamb");
        callback.doSomething("42");
      }

    }

    Just look at how much less clutter there is between the previous two examples!

    Now you’re ready to get your hands dirty!

    Next, in Step 8, I’ll give you an overview of the Examples, just to orient you.

    If you want to jump right into the code, feel free to skip to Step 9, where you’ll create some anonymous classes in three different ways as part of a Vaadin 8 web application.

  8. About the exercises

    To help you get your hands dirty, I’ve put together a sample application that you can get from GitHub. The sample application is a simple Vaadin 8 that lets you create and use anonymous classes in three different ways. 

    The Exercises are marked in the code with TODO comments. Look for the TODO comments, and follow the instructions. Each exercise lets you create an anonymous class in one of three ways:

    • Exercise 1 – Abstract class implementation
    • Exercise 2 – Interface implementation
    • Exercise 3 – Lambda expressions

    There is a bonus exercise that lets you shorten the interface implementation to a lambda expression (a perfect use of a lambda expression) if you’re interested.

    If you get stuck, check out the com.makotojava.learn.recipe.anonymousclasses.solution package, where I’ve written the solution to the exercises. But at least give each exercise a try before peeking at the solution!

    In the next section, there is a video where I show you how to get the code from GitHub, import the code into Eclipse, and much more. So make sure and check that out!

  9. Completing the exercises

    In the video, you see:

    • How to clone the code from Github
    • How to import the code into Eclipse
    • A quick tour through the code
    • An overview of the exercises

     

  10. What's next?

    Learn more about Vaadin. 

    Learn more about WebSphere Liberty.

Join The Discussion