Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to add unimplemented methods?

I am trying to add a listener to a JFrame closing operation:

addWindowListener(new WindowListener() {
    @Override
    public void windowClosing(WindowEvent e) {
        setVisible(false);
    }
});

The thing is that Eclipse keeps telling me I have to "add unimplemented methods", which I assume it gets from the WindowListener. I am confused, though, as to why you need to implement all these other methods as well, if you only need to override one? And if I do add all those other methods, but don't put any content in them e.g.

@Override
public void windowActivated(WindowEvent e) {}

will the default behaviour for this method get lost? Or will it only get overriden if I write something inside the method?

like image 989
Bram Vanroy Avatar asked Dec 25 '22 10:12

Bram Vanroy


2 Answers

If you implement an interface you must implement all methods. That also applies for anonymous classes.

Use WindowAdapter instead of implementing WindowListener

addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        setVisible(false);
    }
});

WindowAdapter is a class that implements WindowListener with empty methods and let you override only the ones you need.

PS: There are also other adapters for other events in swing. E.g. MouseAdapter, KeyAdapter

like image 91
René Link Avatar answered Dec 26 '22 23:12

René Link


Yes, you have to implement all methods.

This is how interfaces work: they define a contract that implementors must follow. If that contract consists of 5 methods then you have to implement all 5 of them.

When there is a consequent number of methods, the Adapter design-pattern is usually put in place: an abstract class that provides default implementation that do nothing is created.

For the WindowListener interface, this is WindowAdapter. So, instead of implementing WindowListener (and all of its methods), you can just extend WindowAdapter and override only the methods you want.

like image 28
Tunaki Avatar answered Dec 27 '22 01:12

Tunaki