Question

My class implements ActionListener. I have implemented the following nested classes below:

JMenuItem mntmNew = new JMenuItem("New...");
    mntmNew.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            doNew(e); //calls to outer class for cleaner code
        }
    });
    mnFile.add(mntmNew);

    JMenuItem mntmLoad = new JMenuItem("Load...");
    mntmLoad.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            doLoad(e); //calls to outer class for cleaner code
        }
    });
    mnFile.add(mntmLoad);

//etc. for the rest of the menu system

However, Eclipse is still telling me that my class must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent e). Can you not implement override methods in a nested class in this way?

Was it helpful?

Solution

Your question:

Can you not implement override methods in a nested class in this way?

The answer is no. Eclipse (actually Java) is complaining that while you're declaring your class as implementing ActionListener you're not giving your class the necessary actionPerformed(...) method in the class's own scope -- and this last part is very important. The class that implements the interface must implement all the interface's required methods in its own scope and not in nested classes. Note that this doesn't prevent you from nesting classes that also implement ActionListener or other interfaces, but regardless, the rule remains that a non-abstract class that implements an interface must override all of the interface's methods.

But since you're not using objects of your class as an ActionListener, the simple solution is to not declare your class as implementing the ActionListener interface. Problem solved. And actually you're far better off not having your GUI class implement your listener interfaces since combining them in one class is asking a class to do too much. In technical terms, it unnecessarily reduces a class's cohesion and risks increasing it's coupling reducing its readability and maintainability.

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