0

I recently came across some seemingly shocking code. For the years I have been programming with Java, never have I seen a class inside a method, yet the user said it was common practice. I tried checking the Oracle Code Conventions documents, but nothing pertaining to this popped up.

The code, showing relevant parts, is below:

public void start(){
    //...
    class startListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            started = true;
        }
    }
    panel.getStartButton().addActionListener(new startListener());
    //...
}

These do seem to compile just fine

What are the rules regarding classes inside methods?

David
  • 15,894
  • 22
  • 55
  • 66
Obicere
  • 2,999
  • 3
  • 20
  • 31
  • 2
    It's common to have anonymous classes, not what you are showing. There's really no reason to have them there. – Sotirios Delimanolis Jan 16 '14 at 03:01
  • @SotiriosDelimanolis I am well-aware of anonymous classes and use them frequently. The difference is that those are documented. – Obicere Jan 16 '14 at 03:02
  • Use a [Local Class](http://stackoverflow.com/questions/2428186/use-of-class-definitions-inside-a-method-in-java) instead. –  Jan 16 '14 at 03:03
  • @Scott thanks for that! I wasn't aware it was under that name, so this is then a copy. I'll flag it to be closed then. – Obicere Jan 16 '14 at 03:05

2 Answers2

2

This is called a local class. From Java Docs:

You can define a local class inside any block (see Expressions, Statements, and Blocks for more information). For example, you can define a local class in a method body, a for loop, or an if clause.

A local class has access to the members of its enclosing class... However, a local class can only access local variables that are declared final.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

I have seen lot of code like this, primarily SWT Code for associating listeners. Though I would have coded it using anonymous local class rather than the named one.

public void start(){
     panel.getStartButton().addActionListener(new startListener() {
       public void actionPerformed(ActionEvent e) {
            started = true;
        }
    });
}

but again this could be just my personal preference.

Vivek Vermani
  • 1,934
  • 18
  • 45