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?
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.