Search code examples
javacode-structure

Is there a name for the this code structure?


Here's a simple case:

    private final MouseAdapter mouse = new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            calculate();
        }
    };

It's a class level field, so calling it an Anonymous Class doesn't seem right. None of the other names or descriptions in the Oracle Tutorials page on Nested Classes seemed to fit either.

I'm guessing it's something along the lines of "Single Use Object" but I'm having a hard time even describing it without saying something like "Class Level Named Anonymous Class"


For those not familiar with Java and AWT, I'm making an instance of a class that has no-operation methods to implement an interface for listening to mouse actions. I want an actual instance so I can add it as multiple types of listeners (wheel, motion, and click) but use the same object for control. The question itself is not AWT specific though.


Solution

  • It is an instance of an anonymous class, there's no need to find a new name for this.

    From Oracle docs :

    Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

    It does not say the instance is to be used only once, but only the class, so there is no contradiction with your case.