Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top